index.js
router.beforeEach((to, from, next) => {
console.log('before each invoked');
if (to.fullPath === '/app') {
// next('/login')//不僅可以寫字符串還可以是一個對象
next({path: '/login', replace})
} else {
next()
}
});
router.beforeResolve((to, from, next) => {
console.log("before resolve invoked")
next();
});
router.afterEach((to, from) =>{
console.log("after invoked")
})
路由守衛(wèi)常用于路由跳轉(zhuǎn)判斷是否需要登錄等,如果需要就跳轉(zhuǎn)到登錄頁面
vue的另外一個鉤子函數(shù) beforeEnter
在routes.js(路由)里面設(shè)置
export default [
{
path: '/login',
component: Login,
name: 'login',
// 進入Login頁面前執(zhí)行的鉤子函數(shù)
beforeEnter (to, from, next) {
console.log("Loginroute before enter")
next();
},
},
]
用于組件內(nèi)部的鉤子
export default{
// 從另外的組件進入該組件前觸發(fā)該鉤子
beforeRouteEnter(to, from, next) {
console.log("todo before enter");
console.log(this) // 這里獲取不到上下文
next(vm => { // next里面有一個回到函數(shù)可以獲取到上下文,把請求到的數(shù)據(jù)塞到vue對象中
console.log(vm.id)
console.log(vm.msg)
vm.test();
});
},
// 同一個組件,param不同的是觸發(fā),常用與同一個組件當(dāng)傳入不通參數(shù)時,展示不同的數(shù)據(jù)
beforeRouteUpdate(to, from, next){
console.log("todo update enter")
next();
},
// 該組件離開跳轉(zhuǎn)到另外的組件時觸發(fā)該鉤子,常應(yīng)用于用戶表單,當(dāng)用戶填了一部分內(nèi)容,需要提醒用戶是否離開頁面
beforeRouteLeave(to, from, next){
console.log("todo leave enter")
if(global.confirm('are you sure')){
next();
}
},
data(){
return{
}
}
}
特別注意:beforeRouteUpdate的觸發(fā)條件

image.png

image.png
當(dāng)從app123,跳轉(zhuǎn)到app456的時候就會觸發(fā)beforeRouteUpdate