Nuxt.js 是一個基於 Vue.js 的通用應用框架。
通過對客户端/服務端基礎架構的抽象組織,Nuxt.js 主要關注的是應用的 UI 渲染。原文可移步我的公眾號文章
🔧 安裝問題 ⚙️
初始化項目失敗
npx nuxi@latest init my_nuxt3_app
1.連接 raw.githubusercontent.com 失敗
“Failed to connect to raw.githubusercontent.com port 443: Connection refused”
本地嘗試 ping raw.githubusercontent.com,發現不通,基本判斷時域名解析的問題。那麼就需要在本機的hosts裏配置 DNS 映射。如下:
➜ /etc cat hosts
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
# GitHub raw content
185.199.108.133 raw.githubusercontent.com
這樣再嘗試 Ping,發現可以訪問了。
➜ ~ ping raw.githubusercontent.com
PING raw.githubusercontent.com (185.199.108.133): 56 data bytes
64 bytes from 185.199.108.133: icmp_seq=0 ttl=47 time=216.667 ms
64 bytes from 185.199.108.133: icmp_seq=1 ttl=47 time=215.707 ms
^C
--- raw.githubusercontent.com ping statistics ---
7 packets transmitted, 5 packets received, 28.6% packet loss
round-trip min/avg/max/stddev = 215.707/251.382/390.085/69.356 ms
➜ ~
2.yarn install 提示認證過期
“error Error: certificate has expired”
解決方法:yarn config set strict-ssl false
🚀 快速入門 🚪
Nuxt3 相比 Nuxt2 還是有挺多變化的,比如使用了Vite、Composables API 、全面支持TS等。先看了 Nuxt2 的中文文檔,遇到一些無解的問題,結果發現官方早都已經是 Nuxt3 了 😅!!!
文件結構
默認只有一個 pages,可以自己創建layouts、components、middleware 這些,約定式路由系統會發揮作用。
js 邏輯寫法
推薦script setup,使用 Composables API 進行開發,基本上都是自動導入的,直接用就行。
接口請求
- 有三種方式
$fetch、useFetch、useAsyncData。其中$fetch只推薦在純客户端運行的項目中運行,否則它發送的接口請求會在server和client各執行一遍。 - 使用
useFetch的第二個參數對象,可以通過{watch: [some_var]}監聽,這樣在some_var發生變化的時候,接口會自動重新執行。 - 在 server 文件夾下創建服務端接口,如創建
server/api/user.js文件:
export default defineEventHandler(async (e) => {
return {
id: 1,
username: "Believer",
};
});
則可通過 const { data: userInfo } = useFetch('/api/user', { params: { id: route.params.id } }) 進行請求。
數據共享
在某個.vue文件中使用useState,則在其它.vue文件中可以通過同變量名的useState進行訪問,數據共享。
A.vue
const counter = useState("counter", () => Math.round(Math.random() * 1000));
B.vue
const counter = useState("counter");
其中 B.vue 中的 counter 值由 A.vue 中的 counter 更新。
頁面跳轉校驗
現在依然可以使用validate進行前置校驗,只不過寫法有變:
user/[id].vue
definePageMeta({
middleware: ["auth"], //會優先於 validate 裏的事件
validate: async (route) => {
return typeof route.params.id === "string" && /^\d+$/.test(route.params.id);
},
});
middleware 裏的邏輯會優先於 validate 執行。
頁面切換效果
如在 app.vue 中定義了名稱為page 的 transition 動畫樣式:
<style>
.page-enter-active,
.page-leave-active {
transition: all 0.4s;
}
.page-enter-from,
.page-leave-to {
opacity: 0;
filter: blur(1rem);
}
</style>
然後需要在 nuxt.config.ts 中開啓:
export default defineNuxtConfig({
compatibilityDate: "2024-11-01",
devtools: { enabled: true },
app: {
pageTransition: { name: "page", mode: "out-in" },
},
});
這樣頁面在切換的時候,就會應用樣式了。如果不通的頁面需要不同的切換效果,則可以在對應頁面中單獨定義。
如在 about.vue 中需要一個名稱為 rotate 的效果。
<script setup>
definePageMeta({
pageTransition: { name: 'rotate' }
})
</script>
當然也不要忘記在 app.vue 中定義名稱為 rotate 的 transition 動畫。
<style>
/* Transition: rotate... */
.rotate-enter-active,
.rotate-leave-active {
transition: all 0.4s;
}
.rotate-enter-from,
.rotate-leave-to {
opacity: 0;
transform: rotate3d(1, 1, 1, 15deg);
}
/* Transition: page... */
.page-enter-active,
.page-leave-active {
transition: all 0.4s;
}
.page-enter-from,
.page-leave-to {
opacity: 0;
filter: blur(1rem);
}
</style>
靜態資源引入
如果是需要工程化處理的資源,比如一張圖片,那麼需要存放在 assets 目錄下,引入時路徑前綴為 ~/assets/ 或 @/assets/。
否則,就存放在 public 目錄下即可,引入時路徑前綴為 /public/your_static_file
解決打包部署時資源文件路徑的問題
需要在 nuxt.config.js 中指定 baseURL。比如我有一個無服務器項目,需要將generate後的頁面部署在 cdn 上,存放在 front/nuxt_1 目錄下,那麼可以這麼寫:
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
compatibilityDate: "2024-11-01",
devtools: { enabled: true },
app: {
pageTransition: { name: "page", mode: "out-in" },
baseURL: "/front/nuxt_1/",
},
});
那麼打包後,靜態資源的路徑會長這樣 /front/nuxt_1/_nuxt/index.jnsm0lKZ.css。
之後就可以通過 www.yourweb.com/front/nuxt_1/index.html 訪問項目首頁。
還有routing、 layout、middleware 的寫法和應用參考 Nuxt3 官網 即可。還有 Nuxt2 裏的 plugins 還沒遇到,應該還在吧,感覺挺好的。
😅 這幾天淺學一下,感受下是否適合手頭的項目做重構(但是文件名約定式路由和各種自動導入用起來真的太舒服了 😂),其它知識點等具體開發項目遇到再記錄。