npm init vue@latest
上面的指令是建立官方的 Vue 框架專案,主要適合 SPA(Single-Page Application),若要使用 SSR(Server-Side Rendering), Vue3 官方推薦使用建立在 Vue3 之上的 Nuxt。
Nuxt 的優點:
- 建立在最新的 Vue3 之上
- 支援自動導入(Auto-imports),預設 components, composables, utils 都不需要再手動 import
- 使用 pages 資料夾內的頁面自動建立路由(router)
- 支援 TypeScript,只要附檔名為 .ts 或是使用 <script lang="ts"> 即可
- 支援 SSR(Server-Side Rendering)
- 支援 CSR(Client-Side Rendering)
- 支援 SSG(Static Site Generation)
- 能夠自訂和使用 Nuxt 模組
建立 Nuxt3 專案
(project-name 請替換為專案名稱)
npx nuxi init project-name
切換到專案目錄下: (project-name 請替換為專案名稱)
cd project-name
使用 yarn 初始化
yarn install
如果沒有安裝 yarn 的話可以使用下面的指令安裝:
npm install --global yarn
第一次建立時可能會詢問是否願意被蒐集資訊,輸入 y 或 n 後按下 Enter 即可
Nuxt collects completely anonymous data about usage.
This will help us improve Nuxt developer experience over time.
Read more on https://github.com/nuxt/telemetry
Are you interested in participating?
啟動開發伺服器並開啟瀏覽器(localhost:3000/)
yarn dev -o
讀取中:
載入完畢:
在建立 Nuxt 專案的時候並沒有和 Vite 建立 Vue 專案一樣詢問那麼多問題,例如要使用 JavaScript 還是 TypeScript、要不要使用 vue-route 等等,但是其實 Nuxt3 基於 Vue3 ,都已經有內建了。
並且檔案也很少,不像 Vue3 Project 還有 main.js, index.html 之類的,因為 Nuxt 會在背後自動處理掉 main.js 應該要做的事情。
建立完專案後所有檔案和資料夾如下:
project/
|-- .nuxt/
|-- node_modules/
|-- README.md
|-- app.vue
|-- nuxt.config.ts
|-- package.json
|-- public
| `-- favicon.ico
|-- tsconfig.json
`-- yarn.lock
在 Nuxt 專案中多了 nuxt.config.ts,他可以讓我們能夠加入其他 Nuxt 模組(Module),不論是自己的專案或是從 npm 取得
在 app.vue 中也只有下面幾行:
<template>
<div>
<NuxtWelcome />
</div>
</template>
目前預設的所有內容都是 NuxtWelcome 這個元件內的,把它移除就會變成空白頁面
基礎路由介紹
Nuxt 使用 vue-router,依據 pages 資料夾中的檔案自動建立路由,不過如果我們只使用 app.vue 頁面並不會自動使用路由。首先先把 app.vue 刪掉,建立一個名稱為 pages 的資料夾
並在 pages 裡面建立檔案,副檔名可以使用 .vue, .js, .jsx, .mjs, .ts, .tsx,只要是符合上述副檔名,就會依照頁面自動建立路由
這裡示範三個檔案:
- pages/index.vue
- pages/user/index.vue
- pages/user/[id].vue
- /
- /user
- /user/:id
到目前為止的檔案和資料夾清單如下:
project/
|-- .nuxt/
|-- node_modules/
|-- README.md
|-- pages
| |-- user/
| | |-- index.vue
| | `-- [id].vue
| `-- index.vue
|-- nuxt.config.ts
|-- package.json
|-- public
| `-- favicon.ico
|-- tsconfig.json
`-- yarn.lock
從路徑中取得參數
剛剛有先使用中括號作為檔案名稱,檔案名稱如下: pages/user/[id].vue中括號中間放的是 id ,代表可以將網址列中的內容做為 id 這個變數讀取:
<template>
<h1>User Page, id = {{ $route.params.id }}</h1>
</template>
如果開啟 http://localhost:3000/user/123 頁面,網頁上就會出現 User Page, id = 123
還有第二種方式可以取得 id:
<template>
<h2>id = {{ id }}</h2>
</template>
<script setup>
const {id} = useRoute().params
</script>
註: <script setup> 一定要有 setup 才能讀取
跳轉頁面
Nuxt3 使用 vue-router,為了不向伺服器重新發送請求所以不直接使用 href 屬性來跳轉連結。在 Vue3 原生專案中是使用 router-link,不過這裡有點不同,是要使用 NuxtLink
<template>
<header>
<nav>
<ul>
<li><NuxtLink to="/">Home</NuxtLink></li>
<li><NuxtLink to="/user">User</NuxtLink></li>
</ul>
</nav>
</header>
<h2>id = {{ id }}</h2>
</template>
<script setup>
const {id} = useRoute().params
</script>
參考資料:
Vue.js - Server-Side Rendering (SSR)
Wiki - Nuxt.js
Nuxt - Installation
留言
張貼留言
如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com