最近學習一下,vue-router的路由鈎子函數,相信只要學前端的小伙伴都接觸的不少,在這里簡單匯總一下,希望對小伙伴們有所幫助。
路由鈎子函數分為三種類型如下:
第一種:全局鈎子函數。
router.beforeEach((to, from, next) => {
console.log('beforeEach')
//next() //如果要跳轉的話,一定要寫上next()
//next(false) //取消了導航
next() //正常跳轉,不寫的話,不會跳轉
})
router.afterEach((to, from) => { // 舉例: 通過跳轉后改變document.title
if( to.meta.title ){
window.document.title = to.meta.title //每個路由下title
}else{
window.document.title = '默認的title'
}
})
第二種:針對單個路由鈎子函數
beforeEnter(to, from, next){
console.log('beforeEnter')
next() //正常跳轉,不寫的話,不會跳轉
}
第三種:組件級鈎子函數
beforeRouteEnter(to, from, next){ // 這個路由鈎子函數比生命周期beforeCreate函數先執行,所以this實例還沒有創建出來
console.log("beforeRouteEnter")
console.log(this) //這時this還是undefinde,因為這個時候this實例還沒有創建出來
next((vm) => { //vm,可以這個vm這個參數來獲取this實例,接着就可以做修改了
vm.text = '改變了'
})
},
beforeRouteUpdate(to, from, next){//可以解決二級導航時,頁面只渲染一次的問題,也就是導航是否更新了,是否需要更新
console.log('beforeRouteUpdate')
next();
},
beforeRouteLeave(to, from, next){// 當離開組件時,是否允許離開
next()
}