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