路由鉤子主要作用是攔截導(dǎo)航,讓他完成跳轉(zhuǎn)或者取消跳轉(zhuǎn)。比如登錄界面輸入了賬號、密碼,主界面需要展示賬號,但是你沒有把 “賬號” 這個(gè)字段保存到 vuex 或者 session 里面,直接跳轉(zhuǎn)會(huì)導(dǎo)致主界面顯示空白,這個(gè)時(shí)候你就需要一個(gè) beforeRouteLeave 路由鉤子,還沒有數(shù)據(jù)的情況下,禁止界面跳轉(zhuǎn),舉例子(偽代碼):
beforeRouteLeave(to,from,next){
if('account' === ' '){
next(false);
}else{
next();
};
};
大概就是這么個(gè)意思,參數(shù) to ——是要跳轉(zhuǎn)到的界面,from —— 從哪個(gè)界面離開,next() —— 是否允許跳轉(zhuǎn),如果是 next(false) ——禁止跳轉(zhuǎn),next({name:LOGIN}) —— 跳轉(zhuǎn)到登錄界面(需要自己手動(dòng)配置路由),next() 或者 next(true) ——允許跳轉(zhuǎn)。
路由鉤子的主要實(shí)現(xiàn)方式有三種
1. 全局實(shí)現(xiàn)
1.1 使用 router.beforeEach 注冊一個(gè)全局的 before 鉤子:
var routes = [{
path:'/route1',
name:'route1',
component:() = > import('./index.vue') //調(diào)用的時(shí)候再開始加載
}]
const router = new VueRouter({
routes;
})
router.beforeEach((to, from, next) => {
next(false);
})
1.2 全局的 after 鉤子,(after 鉤子沒有 next 方法,不能改變導(dǎo)航)
2. 路由獨(dú)享
2.1 配置路由的時(shí)候可以直接增加 beforeEnter,功能類似 before。
var routes = [{
path:'/route1',
name:'route1',
component:() = > import('./index.vue') //調(diào)用的時(shí)候再開始加載
beforeEnter: (to, from, next) => {
next();
}
}]
3. 組件內(nèi)實(shí)現(xiàn)的鉤子
3.1 beforeRouteEnter
在導(dǎo)航確認(rèn)之前調(diào)用,新組件的 beforeCreate 之前調(diào)用,所以特別注意它的 this 是 undefined
3.2 beforeRouteUpdate
用法:點(diǎn)擊更新二級導(dǎo)航時(shí)調(diào)用。
3.3 beforeRouteLeave
離開當(dāng)前界面之前調(diào)用,用法:1. 需要的保存或者刪除的數(shù)據(jù)沒有完成當(dāng)前操作等等原因,禁止界面跳轉(zhuǎn)。