參考資料:vue-router
1、beforeRouteEnter的使用場景:組件複用;路由跳轉
beforeRouteEnter (to, from, next) {
// 在渲染該組件的對應路由被 confirm 前調用
// 不!能!獲取組件實例 `this`
// 因爲當守衛執行前,組件實例還沒被創建
console.log(to)
console.log(from)
console.log(next)
next(vm => {
console.log(vm)
})
}
使用案例:校驗用戶是否登錄:
beforeRouteEnter: (to, from, next) => {
let user_info = Storage.get(G.storage_key);
if (to && to.path !== "/login") {
if (_.isEmpty(user_info)) {
logout();
} else {
next();
}
} else if (to && to.path === G.loginPage) {
if (!_.isEmpty(user_info)) {
next(".hme/);
} else {
next();
}
}
},
2、beforeRouteUpdate
beforeRouteUpdate (to, from, next) {
// 在當前路由改變,但是該組件被複用時調用
// 舉例來說,對於一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候,
// 由於會渲染同樣的 Foo 組件,因此組件實例會被複用。而這個鉤子就會在這個情況下被調用。
// 可以訪問組件實例 `this`
// 別忘了調用next
}
使用案例:
beforeRouteUpdate(to, from, next) {
var isNeedRedirect = this.isNeedRedirect(to.path);
if (isNeedRedirect) {
next({name: '_404'});
} else {
next();
}
next();
},
3、beforeRouteLeave
beforeRouteLeave (to, from, next) {
// 導航離開該組件的對應路由時調用
// 可以訪問組件實例 `this`
}