路由守卫
-
作用:对路由进行权限控制
-
分类:全局守卫、独享守卫、组件内守卫
-
全局守卫:
下边代码是写到router文件夹下的index.js文件中的
//全局前置守卫:初始化时执行、每次路由切换前执行
router.beforeEach((to,from,next)=>{
console.log('beforeEach',to,from)
if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制
if(localStorage.getItem('school') === 'atguigu'){ //权限控制的具体规则
next() //放行
}else{
alert('暂无权限查看')
// next({name:'guanyu'})
}
}else{
next() //放行
}
})
//全局后置守卫:初始化时执行、每次路由切换后执行
router.afterEach((to,from)=>{
console.log('afterEach',to,from)
if(to.meta.title){
document.title = to.meta.title //修改网页的title
}else{
document.title = 'vue_test'
}
})
注释:上边的to,from分别代表想要跳转的组件以及跳转前的组件
在router文件夹下的index.js文件中每一个路由都可以配置meta
属性meta中的每一组key-value都是程序员自己定义的哦
- 独享守卫:
下边代码是写到router文件夹下的index.js文件中路由下边的
beforeEnter(to,from,next){
console.log('beforeEnter',to,from)
if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制
if(localStorage.getItem('school') === 'atguigu'){
next()
}else{
alert('暂无权限查看')
// next({name:'guanyu'})
}
}else{
next()
}
}
- 组件内守卫:
注意:写在组件(.vue)文件中
注意:必须是通过路由规则,而且beforeRouteEnter 是在进入这个组件时候才会被调用而beforeRouteLeave 是在离开个组件时候被调用,
要与全局前置/后置路由守卫进行区分
//进入守卫:通过路由规则,进入该组件时被调用
beforeRouteEnter (to, from, next) {
},
//离开守卫:通过路由规则,离开该组件时被调用
beforeRouteLeave (to, from, next) {
}