路由鉤子函數(shù)分為三種類型如下:
第一種:全局鉤子函數(shù)。
router.beforeEach((to, from, next) => {
console.log('beforeEach')
//next() //如果要跳轉(zhuǎn)的話,一定要寫上next()
//next(false) //取消了導(dǎo)航
next() //正常跳轉(zhuǎn),不寫的話,不會跳轉(zhuǎn)
})
router.afterEach((to, from) => { // 舉例: 通過跳轉(zhuǎn)后改變document.title
if( to.meta.title ){
window.document.title = to.meta.title //每個路由下title
}else{
window.document.title = '默認(rèn)的title'
}
})
第二種:針對單個路由鉤子函數(shù)
beforeEnter(to, from, next){
console.log('beforeEnter')
next() //正常跳轉(zhuǎn),不寫的話,不會跳轉(zhuǎn)
}
第三種:組件級鉤子函數(shù)
beforeRouteEnter(to, from, next){ // 這個路由鉤子函數(shù)比生命周期beforeCreate函數(shù)先執(zhí)行,所以this實例還沒有創(chuàng)建出來
console.log("beforeRouteEnter")
console.log(this) //這時this還是undefinde,因為這個時候this實例還沒有創(chuàng)建出來
next((vm) => { //vm,可以這個vm這個參數(shù)來獲取this實例,接著就可以做修改了
vm.text = '改變了'
})
},
beforeRouteUpdate(to, from, next){//可以解決二級導(dǎo)航時,頁面只渲染一次的問題,也就是導(dǎo)航是否更新了,是否需要更新
console.log('beforeRouteUpdate')
next();
},
beforeRouteLeave(to, from, next){// 當(dāng)離開組件時,是否允許離開
next()
}