例:
router.beforeEach((to, from, next) => {
let isLogin = Vue.prototype.$loginInfo.info.is_login
if (to.matched.length === 0) { //沒(méi)有匹配到當(dāng)前路由
next('/error')
} else if (!isLogin && to.path !== '/login' && to.path !== '/register' && to.path !== '/password') {
//如果沒(méi)有登錄,跳轉(zhuǎn)到登錄頁(yè)面
next('/login')
} else {
if ((to.path === '/login' || to.path === '/register' || to.path === '/password' || to.path === '/error') && isLogin) {
//如果已經(jīng)登錄,卻嘗試訪問(wèn)登錄頁(yè)面或者錯(cuò)誤頁(yè)面,將繼續(xù)保持原本的頁(yè)面
next(from.path)
} else {
next()
}
}
// next()
})
全局后置鉤子
你也可以注冊(cè)全局后置鉤子,然而和守衛(wèi)不同的是,這些鉤子不會(huì)接受 next 函數(shù)也不會(huì)改變導(dǎo)航本身:
router.afterEach((to, from) => {
// ...
})
路由獨(dú)享的守衛(wèi)
你可以在路由配置上直接定義 beforeEnter 守衛(wèi):
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})