路由守卫包括全局守卫(beforeEach())、路由独享守卫(beforeEnter())、组件内守卫(beforeRouteEnter()、beforeRouteLeave())
1.全局守卫(beforeEach())
1.全局前置路由守卫beforeEach(),初始化的时候调用,每次路由切换前调用。
在定义路由router的时候,通过router.beforeEach()来做一些权限管理,比如一个页面需要登录权限,登录了的才能进入这个页面。
在router.js文件
router.beforeEach((to,from,next)=>{
if(to.path==="/home/news"){//如果要到/home/mews
if(localStorage.getItem('school')==='atguigu'){//条件1 满足 就跳转
next()
}else{
alert(‘学校不对,无权限查看’)
}else{
next()
}
}
})
to表示要到的路由,from表示从哪个路由跳转。next()表示放行(即跳转)
2.全局后置后卫afterEach(),初始化的时候调用,每次切换之后调用。
router.afterEach((to,from)=>{
document.title='嘻嘻'
})
可以在路由配置的时候设置元信息meta,比如上面的不光是to.path==="/home/news
需要权限,很多路由都需要这个权限,解决办法是在路由配置的时候在meta里表明
{
path:'/home/news',
component:News,
meta:{
isAuth:true
}
}
在验证时候
router.beforeEach((to,from,next)=>{
if(to.meta.isAuth){如果要到的路由需要meta.isAuth
if(localStorage.getItem('school')==='atguigu'){//条件1 满足 就跳转
next()
}else{
alert(‘学校不对,无权限查看’)
}else{
next()
}
}
})
2.路由独享守卫
在定义路由的时候,
path:"/home/news",
name:"news",
component:News,
beforeEnter(to,from,next){
if(to.meta.isAuth){
if(localStorage.getItem('school'==='atguigu'){
next()
}else{
alert(‘无权查看’)
}
}
}else{
next()
}
在进入这个路由之前,增加条件,满足条件就跳转。
组件内的守卫
和data、created、mounted、methods处于平等关系
1.进入守卫beforeRouteEnter()
进入守卫,通过路由匹配规则,进入该组件时被调用,在组件的.vue文件
beforeRouteEnter(to,from,next){
if(to.meta.isAuth){
if(localStorage.getItem('school')==='atguigu'){
next()
}else{
alert(‘无权查看’)
}
}else{
next()
}
}
2.离开守卫beforeRouteLeave()
通过路由规则,离开该组件被调用
beforeRouteLeave(to,from,next){
next()
}