路由守卫的作用: 对路由进行权限控制.
分类: 全局守卫,独享守卫,组件内守卫.
1. 全局守卫
//全局前置路由守卫, 初始化和每次路由切换时调用
router.beforeEach((to,from,next) => {
console.log("前置路由守卫",to,from);
//next();//放行
if(to.meta.isAuth){//判断是否需要鉴权
if(localStorage.getItem('school') === 'vue'){
next();
}else{
alert("学校信息不对,无权查看");
}
}else{
next();
}
})
//全局后置路由守卫
router.afterEach((to,from,next) => {
document.title = to.meta.title || 'vue系统';
console.log("后置路由守卫",to,from,next);
})
2. 独享守卫
{
path:'news',
component:News,
meta:{isAuth:true,title:'新闻'},
beforeEnter:(to,from,next) => {
if(to.meta.isAuth){
if(localStorage.getItem("school") === 'vue'){
next();
}else{
console.log("请登录");
}
}
}
},
3. 组件内守卫
export default {
// eslint-disable-next-line vue/multi-word-component-names
name: 'About',
//通过路由规则进入该组件时调用
beforeRouteEnter(to,from,next){
console.log("进入About",to,from,next);
next();//放行
},
//通过路由规则离开该组件时调用
beforeRouteLeave(to,from,next){
console.log("离开About",to,from,next);
next();//放行
}
}