這里只記錄一些常用的鈎子,更多的還是去看官網吧。
一、服務端鈎子
nuxtServerInit() 通常用於初始化一些東西在狀態樹中
這里給出了一些基本的使用,該文件為store/index.js
// state export function state() { return { bNav: false, bLoading: false } } // mutations export const mutations = { M_UPDATE_NAV(state, payload) { state.bNav = payload }, M_UPDATE_LOADING(state, payload) { state.bLoading = payload; } } // actions export const actions = { nuxtServerInit(store, context) { // 初始化東西到狀態樹 } } // getters export const getters = { getNav(state) { return state.bNav ? '顯示' : '隱藏' } } export default {namespaced: true, state, mutations, actions, getters}
middleware 中間件,可使用中間件的地方:
1.nuxt.config.js中配置middleware
使用方法: 在middleware文件夾下建一個js文件,名稱自定義 我們這里建一個auth.js
內容隨便寫
export default({store, route, redirect, params, query, req, res}) => { // 全局守衛業務 console.log('middleware nuxt.config.js') }
然后再nuxt.config.js中配置
router: { middleware: 'auth', },
2.layout 布局頁面使用
3. 組件中使用
<script> export default {
data() {
return {}
}, middleware() { console.log("頁面級別的middleware") } } </script>
asyncData() 讀取數據,返回給組件,這里我們可以做一些異步的數據請求,返回給組件。
fetch() 和asyncData類似,只不過返回數據給redux狀態樹。
validate() 做一些校驗業務,返回Boolean值,true為通過,false則跳到錯誤頁面。
具體使用方式在下篇文章!!
二、服務端和客戶端
beforeCreate()
created()
這兩個鈎子可能運行在客戶端(CSR)也可能在服務端(SSR)
建一個頁面測試一下。。。
<template> <h1>登錄頁</h1> </template> <script> export default { beforeCreate() { // window是瀏覽器獨有的,服務端不會有 console.log("beforeCreate", window); }, }; </script> <style> </style>
訪問對應頁面,你有幾率看到錯誤信息,沒有的話多刷新幾次。
三、客戶端
客戶端的生命周期鈎子和vue一致,這里不做過多的介紹。
beforeMount()
mounted()
beforeUpdate()
updated()
beforeDestory()
destoryed()
activated()
deactivated()