全局守衛
vue-router全局有三個守衛:
- router.beforeEach 全局前置守衛 進入路由之前
- router.beforeResolve 全局解析守衛(2.5.0+) 在beforeRouteEnter調用之後調用
- router.afterEach 全局後置鉤子 進入路由之後
用法:
// main.js 入口文件
// to和from是將要進入和將要離開的路由對象this.$route
// next:Function 這個參數是個函數,且必須調用,否則不能進入路由(頁面空白)。
// 通過next()方法進行路由跳轉
import router from './router'; // 引入路由
router.beforeEach((to, from, next) => {
// 通常用於常見的登錄權限驗證
next();
});
router.beforeResolve((to, from, next) => {
next();
});
router.afterEach((to, from) => {
// 不能使用next()方法
console.log('afterEach 全局後置鉤子');
});
路由獨享守衛
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// 調用順序在全局前置守衛後面,不會被全局守衛覆蓋
// ...
}
}
]
})
路由組件內的守衛:
- beforeRouteEnter 進入路由前
- beforeRouteUpdate (2.2) 路由複用同一個組件時
- beforeRouteLeave 離開當前路由時
用法:
beforeRouteEnter (to, from, next) {
// 在路由獨享守衛後調用 不!能!獲取組件實例 `this`,因爲組件實例還沒被創建
......
},
beforeRouteUpdate (to, from, next) {
// 在當前路由改變,但是該組件被複用時調用 可以訪問組件實例 `this`
// 舉例來說,對於一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候,
// 由於會渲染同樣的 Foo 組件,因此組件實例會被複用。而這個鉤子就會在這個情況下被調用。
......
},
beforeRouteLeave (to, from, next) {
// 導航離開該組件的對應路由時調用,可以訪問組件實例 `this`
// 導航離開該組件的對應路由時調用,我們用它來禁止用戶離開,
// 比如還未保存草稿,或者在用戶離開前,將setInterval銷燬,防止離開之後,定時器還在調用。
......
}