路由守卫:保护路由的安全。控制路由跳转权限。路由跳转有两种方式:1 、<router-link>方式,2、编程式跳转。路由守卫:控制路由在符合某种条件下才能完成跳转。
一、全局路由守卫
全局,所有的路由,此时需要找路由器router,可以是在src/router/index.js文件中,也可以是在main.js中,亦或者是在与某个引入了src/router/index.js文件暴露的router的perssion.js文件中(需要在main.js中引入),借助beforeEach()/afterEach()实现
1. 全局前置路由守卫
前置,在路由切换之前判断,不符合条件则不跳转。在初始化的时候调用,在路由切换的时候调用
// to:要去的路由,from:当前路由,next:触发跳转
router.beforeEach((to, from, next) => {
...逻辑
next()
}
2.全局后置路由守卫
后置,在跳转之后判断,不管符不符合,路由都会跳转,浏览器地址栏都会变化,多用于跳转后修改页签标题等。
// to:要去的路由,from:当前路由
router.afterEach((to, from) => {
扫描二维码关注公众号,回复: 14851071 查看本文章...逻辑
}
二、独享路由守卫
某一个路由单独享有的路由守卫,需要在配置路由的地方,添加beforeEnter函数,只有前置,没有后置
{
name: 'home',
path: '/home',
component: () => import('@/views/home/Home),
meta: { isAuth: true, title: '首页' },
beforeEnter: (to, from, next) => {
/*... //逻辑
if(to.meta.isAuth){
if(条件){
next()
}
else {
alert('暂无权限查看')
}
}
else{
next()
}
*/
}
}
三、组件内路由守卫
组件内的路由守卫,属于data,methods等的同等级配置选项
// 通过路由规则进入该组件时被调用
// 不可以访问组件实例 `this`
beforeRouteEnter(to, from, next){
console.log('beforeRouteEnter', to. from)
next()
}
// 在当前路由改变,但是该组件被复用时调用
// 如 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候
// 可以访问组件实例 `this`
beforeRouteUpdate(to, from, next){
console.log('beforeRouteEnter', to. from)
next()
}
// 通过路由规则离开该组件时被调用,跳转结束,而是离开该组件
// 可以访问组件实例 `this`
beforeRouteLeave(to, from, next){
console.log('beforeRouteEnter', to. from)
next()
}