導(dǎo)航”表示路由正在發(fā)生改變。
to: Route: 即將要進(jìn)入的目標(biāo) 路由對(duì)象
from: Route: 當(dāng)前導(dǎo)航正要離開的路由
next: Function: 一定要調(diào)用該方法來 resolve 這個(gè)鉤子。執(zhí)行效果依賴 next 方法的調(diào)用參數(shù)汞贸。
next(): 進(jìn)行管道中的下一個(gè)鉤子。如果全部鉤子執(zhí)行完了凤类,則導(dǎo)航的狀態(tài)就是 confirmed (確認(rèn)的)。
全局守衛(wèi)
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// ...
})
const arr = ["my"]
router.beforeEach((to, from, next) => {
if (arr.includes(to.name)) {
let userId = localStorage.getItem("userId")
if (userId) {
next()
} else {
next("/my")
}
} else {
next()
}
})
全局后置鉤子
你也可以注冊(cè)全局后置鉤子,然而和守衛(wèi)不同的是物延,這些鉤子不會(huì)接受 next 函數(shù)也不會(huì)改變導(dǎo)航本身:
router.afterEach((to, from) => {
// ...
})
獨(dú)享守衛(wèi)
與全局前置守衛(wèi)的方法參數(shù)是一樣的
const router = new VueRouter({
routes: [
{
path: '/shop/:id',
component: 'shop',
beforeEnter: (to, from, next) => {
// ...
}
}
]
})
組件內(nèi)守衛(wèi)
const Foo = {
template: `...`,
beforeRouteEnter (to, from, next) {
if(to.params.id < 10){
next()
}eslse{
next('/login')
}
1。在渲染該組件的對(duì)應(yīng)路由被confirm前調(diào)用
2仅父。不叛薯!能!獲取組件實(shí)例 `this`
3笙纤。因?yàn)楫?dāng)守衛(wèi)執(zhí)行前耗溜,組件實(shí)例還沒被創(chuàng)建
},
beforeRouteUpdate (to, from, next) {
1. 在當(dāng)前路由改變,但是該組件被復(fù)用時(shí)調(diào)用
2 舉例來說粪糙,對(duì)于一個(gè)帶有動(dòng)態(tài)參數(shù)的路徑 /foo/:id强霎,在 /foo/1 和 /foo/2 之間跳轉(zhuǎn)的時(shí)候,
3 由于會(huì)渲染同樣的 Foo 組件蓉冈,因此組件實(shí)例會(huì)被復(fù)用城舞。而這個(gè)鉤子就會(huì)在這個(gè)情況下被調(diào)用。
4 可以訪問組件實(shí)例 `this`
},
beforeRouteLeave (to, from, next) {
1 導(dǎo)航離開該組件的對(duì)應(yīng)路由時(shí)調(diào)用
2 可以訪問組件實(shí)例 `this`
}
}
路由元信息
定義路由的時(shí)候可以配置 meta 字段
meta: { requires: true }
routes 配置中的每個(gè)路由對(duì)象為 路由記錄寞酿。路由記錄可以是嵌套的家夺,因此,當(dāng)一個(gè)路由匹配成功后伐弹,他可能匹配多個(gè)路由記錄
導(dǎo)航守衛(wèi)中的路由對(duì)象 的 $route.matched 數(shù)組
全局導(dǎo)航守衛(wèi)中檢查元字段
router.beforeEach((to,from,next)=>{
if(to.matched.some(record=>record.meta.requires)){
if(!localStorage.getItem("token")){
next({
name:'login'
})
} else {
next()
}
} else{
next()
}
})