vue中路由导航守卫,也叫做路由钩子函数,可以对用户要跳转的路由做一次检查,符合条件的就放行,不符合的强制用户跳转至登陆页面。
路由的导航守卫分为三种:
第一种:全局路由导航守卫:全局前置路由守卫和全局后置路由守卫。
全局前置路由守卫 router.beforeEach(切换之前调用,to、from、next参数)
//全局前置守卫,初始化时执行、每次路由切换前执行
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.beforeEach((to,from,next) =>{
if(to.path === '/home/news' || to.path === '/home/message'){
if(localStorage.getItem('school') === 'atguigu'){
next()
}else{
alert('用户名不符,无权查看')
}
}else{
next()
}
})
export default router
全局后置路由守卫router.afterEach(切换之后调用,to、from,没有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'
}
})
// 例如:当我们更换组件之后,要求页面的title也会跟着修改
router.afterEach((to,from) => {
document.title = to.meta.title || '学习系统'
})
第二种:组件内路由守卫(在组件内编写)
//进入守卫:通过路由规则,进入该组件时被调用
beforeRouteEnter(to,from,next){},
//离开守卫:通过路由规则,离开该组件时被调用
beforeRouteLeaver(to,from,next){},
// 通过路由规则,进入该组件时被调用
beforeRouteEnter(to,from,next){
//判断是否需要鉴定一下权限
if(to.meta.isAuth){
if(localStorage.getItem('school') === 'atguigu'){
next(vw=>{
alert('Hello' + vm.name)
})
}else{
alert('无权限')
}
}else{
next()
}
}
// 离开该组件时被调用
beforeROuteLeave(to,from,next){
if(confirm("确定离开此页面吗?") == true){
next();
}else{
next(false);
}
}
第三种:路由独享守卫beforeEnter(某一个路由所单独享用的,只有前置没有后置)
// 对某一个路由做出限制
beforeEnter(to,from,next){
console.log('beforeEnter',to,from)
if(to.meta.isAuth){ // 判断当前路由是否需要进行权限控制
if(localStorage.getItem('school') === 'atguigu'){
next()
}else{
alert('暂无权限查看')
}
}else{
next()
}
}
{
path: '/',
name: 'home',
component: HomeView,
// 嵌套路由(子路由)
children:[
{
path:'/home/one',
component:one,
// 路由单独钩子(router独享守卫)
beforeEnter:(to,from,next)=>{
console.log('进入前执行');
next();
}
}
]
}