考慮一下這個需求:當頁面發生跳轉時,自動更改頁面的標題。比如跳轉到home頁面,標題改爲首頁,跳轉到about頁面,標題改爲關於。
首先,可以通過生命週期函數實現這個需求,但使用生命週期函數的話,需要在每一個組件中都添加實現代碼,如果組件過多的話,這將不是一個好的選擇。
這時,就可以考慮使用導航守衛的功能。
什麼是導航守衛呢?導航守衛對全局跳轉進行監聽,並且可以根據你的需求在跳轉時執行一些代碼。
const router = new Router({
routes: [
{
path:'/',
redirect:'/home'
},
{
path:'/home',
component:() => import('../components/home'),
meta:{
title:'首頁'
}
},
{
path:'/about',
component:() => import('../components/about'),
meta:{
title:'關於'
}
}
],
mode:'history'
})
//導航守衛
router.beforeEach((to,from,next) => {
document.title = to.meta.title //注意這裏的用法,參數to的類型實際上是route類型,因此我們可以給每個route添加一個meta屬性,如上
next() //next()在源碼中已經被實現好了,這裏需要加入它
})
這裏需要注意的是,一旦某個路由是嵌套路由,那麼顯示的title將會變成undefined,這是因爲path爲類似於 /home/news 的格式,參數to在處理它時出現了問題。
想要解決嵌套路由的問題,只需要:
router.beforeEach((to,from,next) => {
document.title = to.matched[0].meta.title
next()
})
另外,既然有beforeEach()
,其實容易想到應該還有afterEach()
,afterEach()
用於在跳轉之後處理某些操作。
//afterEach沒有next參數
router.afterEach((to,from) => {
...
})