# Nuxt 3 專案 | 環境安裝 ## 建立 Nuxt3 專案 安裝指令 ```bash= npx nuxi@latest init <project-name, eg. Nuxt3Project> ``` 進入專案目錄 ```bash= cd Nuxt3Project ``` 安裝專案資源 ```bash= npm i ``` 運行專案 ```bash= npm run dev ``` 1. 運行過程若沒有 error ,可以開啟 http://localhost:3000 確認專案是否能夠正常開啟。 2. Nuxt3 預設有導入 typescript ## 安裝狀態管理工具 Pinia 這是 Nuxt3 官方推薦的工具, 指令會一次安裝 `@pinia/nuxt` 和 `pinia` ```bash= npx nuxi@latest module add pinia ``` ### 設定 nuxt.config.ts ```bash= export default defineNuxtConfig({ // ... other options modules: [ // ... '@pinia/nuxt', ], }) ``` ### 重新運行專案 確認工具安裝後未影響專案運行 ```bash= npm run dev ``` ## 使用 Pinia 管理登入狀態 建立 `stores/auth.ts`,若目錄不存在就手動建立一個 ```typescript= interface UserData { number: string name: string } export const useAuthStore = defineStore('auth', { state: ()=> ({ isLoggedIn: false, user: null as UserData | null }), actions: { login(userData: UserData) { // fetch api ... this.isLoggedIn = true, this.user = userData }, logout() { this.isLoggedIn = false, this.user = null } } }) ``` ### 建立會員登入頁面 建立 `pages/member/index.vue`,不需要 `import { useAuthStore } from '@/stores/auth'`,即可使用 `useAuthStore()` ```html= <template> <div> 會員登入 <div> 手機 <input v-model='mobile' type='text' required> </div> <div> <button v-on:click='handleLogin'>登入</button> </div> </div> </template> <script setup> import { ref } from 'vue' const mobile = ref(''); const authStore = useAuthStore() const handleLogin = () => { if (條件) { authStore.login({mobile: mobile.value, name: '王大明'}) useRouter().push('/Member/profile') // 跳轉到會員資料頁 } else { // 登入失敗 } } </script> ``` --- ### Reference - [Nuxt v3.15 官方網站](https://nuxt.com/docs/getting-started/installation) - [Pinia 官方網站](https://pinia.vuejs.org/ssr/nuxt.html#Installation) --- > 系列:[`Nuxt 3 專案`](https://hackmd.io/@elzuoc?tags=%5B"Nuxt+3+專案"%5D) > 上一篇: > 下一篇: ###### tags: [`Nuxt 3 專案`](https://hackmd.io/@elzuoc?tags=%5B"Nuxt+3+專案"%5D) ###### 文章若有任何錯誤,還請不吝給予留言指正,謝謝大家!