全局导航守卫
是在做权限验证的时候会使用导航守卫 。1.前置守卫
meta
: { may
: true }
router
.beforeEach((to
, from, next
) => {
if (to
.matched
.some(item
=> item
.meta
.may
)) {
let id
= window
.localStorage
.getItem("id")
if (id
) {
next()
} else {
next({ name
: "login" })
}
} else {
next()
}
})
注意:next 方法必须要调用,否则钩子函数无法 resolved
后置钩子函数
router
.afterEach((to
,from) => {
if(to
.meta
&& to
.meta
.title
){
document
.title
= to
.meta
.title
}else{
document
.title
= "666"
}
})
组件内守卫
*** beforeRouteEnter(to
,from,next
){
if(to
.params
.id
<10)
next() 登录
}else{
next("/home") 返回首页
}
},
beforeRouteUpdate (to
, from, next
) {
next() 只要改变触发就执行next()
},
beforeRouteLeave (to
, from, next
) {
next()
}
from是要从哪里来
next就是成功就执行
路由独享守卫
const router
= new VueRouter({
routes
: [
{
path
: '/foo',
name
:"foo"
component
: Foo
,
beforeEnter
: (to
, from, next
) => {
}
}
]
})
全局守卫
router.beforeResolve 注册一个全局守卫,和 router.beforeEach 类似
const router
= new VueRouter({
})
const login
=["order","my"]
router
.beforeEach((to
,from,next
)=>{
if(login
.includes(to
.name
)){
let userId
=window
.localStroage
.getItem("userId")
if(userId
){
next()
}else{
next("/login")
}
}else
next()
})
export default router
;