目录
(一)什么是路由守卫
路由守卫:路由在跳转前、后过程中的一些钩子函数,这些函数可以让你操作一些其他的事,在后台管理中设置权限时经常看到,在实现路由跳转前校验是否有权限,有权限就可以通过,反之就会被执行其他操作。
(二)路由守卫的分类
(1)全局守卫
beforeEach和afterEach,其中有to,from,next参数
对于beforeEach传三个参数,afterEach传to,from两个参数即可
to:为即将进入的目标对象,可以用to.path或者to.name调用路由对象中的属性
from:也为从哪里来,当前正要离开的路由
next:其为一个方法,表示放行有权限。
路由守卫写在router下的index.js中 ,为了书写便利,将自己需要的数据写在meta里面
{
name:'xinwen',
path:'news',
component:News,
meta:{isAuth:true,title:'新闻'}//想让谁有权限就写在谁的路由配置里面
},
1、前置全局路由守卫
router.beforeEach((to, from, next) => {
if(to.meta.isAuth){
if(localStorage.getItem('school')==='hkd2'){
next()
}
else{
alert('学校名不对,无权限查看')
}
}else{
next()
}
})
2、后置路由守卫
路由跳转之后执行,可以用作跳转路由后更改网页名
// (全局后置路由守卫)切换后
router.afterEach((to,from)=>{
document.title=to.meta.title||"小开心系统"
})
(2)独享守卫
注意 :独享路由守卫只有前置没有后置,用于向单独的给某个路由设置权限,在配置路由的时候配置。
{
name:'xinwen',
path:'news',
component:News,
meta:{isAuth:true,title:'新闻'},
beforeEnter(to,from,next){
if(to.meta.isAuth){
if(localStorage.getItem('school')==='hkd'){
next()
}
else{
alert('学校名不对,无权限查看')
}
}else{
next()
}
}
},
(3)组件内守卫
写在组件(.vue)里面
beforeRouteEnter:通过路由规则,进入该组件时被调用
beforeRouteLeave:通过路由规则,进入该组件时被调用
export default {
name:'About',
beforeRouteEnter(to,from,next){
console.log('about---beforeRouteEnter',to,from)
if(to.meta.isAuth){
if(localStorage.getItem('school')==='hkd'){
next()
}
else{
alert('学校名不对,无权限查看')
}
}else{
next()
}
},
beforeRouteLeave(to,from,next){
console.log('about---beforeRouteLeave',to,from)
next()
}
}