路由守卫
配置路由守卫应在暴露前配置
首先先给需要鉴权的路由设置好meta配置项。
{
name: 'zhuye',
path: '/home',
component: Home,
children: [
{
name: 'xinwen',
path: 'news',
component: News,
//isAuth是否需要身份验证,title设置网页标题
meta: { isAuth: true, title:'新闻' }
},
]
}
]
}
全局守卫
beforeEach是Vue Router中的一个钩子函数,用于在路由切换前执行一些操作。可以利用beforeEach钩子函数实现某些全局的路由拦截控制。
to:要跳转的目标路由对象,from:当前导航正要离开的路由,next:调用该方法后,表示进入下一个路由
//全局前置守卫:初始化时执行、每次路由切换前执行
router.beforeEach((to,from,next=>{
if(to.meta.isAuth{ //判断当前路由是否需要进行权限控制
if(localStorage.getItem('school' === 'atguigu'{ //权限控制的具体规则
next( //放行
}else{
alert('暂无权限查看'
}
}else{
next( //放行
}
}
afterEach是Vue Router中的一个钩子函数,用于在路由完成跳转后执行一些操作。可以利用afterEach钩子函数实现某些全局的路由跳转后的处理
to:成功跳转的目标路由对象。from:当前导航正要离开的路由
//全局后置守卫:初始化时执行、每次路由切换后执行
router.afterEach((to,from=>{
if(to.meta.title{
document.title = to.meta.title //修改网页的title
}else{
document.title = 'vue_test'
}
}
独享守卫
可以让某个路由及其所有子路由独享一个路由守卫。这个路由守卫与全局前置守卫beforeEach
相似,但是只作用于该路由及其子路由。
beforeEnter(to,from,next{
if(to.meta.isAuth{ //判断当前路由是否需要进行权限控制
if(localStorage.getItem('school' === 'atguigu'{
next(
}else{
alert('暂无权限查看'
}
}else{
next(
}
}
组件内守卫
在组件内部使用Vue Router提供的路由守卫来控制组件的进入、离开、更新等操作。
//进入守卫:通过路由规则,进入该组件时被调用
beforeRouteEnter (to, from, next {
... //里面的配置和前面差不多
},
//离开守卫:通过路由规则,离开该组件时被调用
beforeRouteLeave (to, from, next {
...
}