其他分享
首页 > 其他分享> > Vue-Router 路由守卫

Vue-Router 路由守卫

作者:互联网

vue-router 路由共分为三大类:

  • 全局守卫

  • 路由独享守卫

  • 路由组件内的守卫

 守卫方法接收三个参数:
    to:即将要进入的目标路由对象
    from:当前导航正要离开的路由
    next:执行下一步
    1). next():进入管道中的下一个钩子,如果全部的钩子执行完了,则导航的状态就是     confirmed(确认的)
    2). next(false):这代表中断掉当前的导航,即 to 代表的路由对象不会进入,被中断,此时该表 URL 地址会被重置到 from 路由对应的地址
    3). next(‘/’) 和 next({path: ‘/’}):在中断掉当前导航的同时,跳转到一个不同的地址
    4).next(error):如果传入参数是一个 Error 实例,那么导航被终止的同时会将错误传递给 router.onError() 注册过的回调

注意:next 方法必须要调用,否则钩子函数无法 resolved

 /**
     * @param {to} 将要去的路由
     * @param {from} 出发的路由
     * @param {next} 执行下一步
     */
    router.beforeEach((to, from, next) => {
        document.title = to.meta.title || '卖座电影';
        if (to.meta.needLogin && !$store.state.isLogin) {
            next({
                path: '/login'
            })
        } else {
            next()
        }
    })
 

全局守卫有三个,分别是:

  • router.beforeEach         全局前置守卫 进入路由之前执行
  • router.afterEach         全局后置守卫  和 beforeEach() 相比,这个router方法是在路由进入之后触发,并且少了一个参数next(),进入路由之后执行
  • router.beforeResolve          全局解析守卫    和 router.beforeEach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。

(1) router.beforeEach

router.beforeEach((to, from, next) => {
  if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  // 如果用户未能验证身份,则 `next` 会被调用两次
  next()
})
// GOOD
router.beforeEach((to, from, next) => {
  if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  else next()
})

​​​​​​

(2) router.afterEach       

router.afterEach((to, from) => {
  // ...
})

(3) router.beforeResolve      

// 全局解析守卫
// 和 router.beforeEach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。
router.beforeResolve((to, from, next) => {
    console.log('beforeResolve全局解析守卫被调用')
    next()
})

路由独享守卫: beforeEnter

如果你不想全局配置守卫的话,你可以为某些路由单独配置守卫beforeEnter

使用方法与全局守卫相同

不同的是:全局守卫可以作用于全局,路由独享守卫只作用于被设置守卫的路由

        //登录模块
        path: '/login',
        component: () => import('@/views/login'),
        beforeEnter: (to, from, next) => {
            if (to.meta.needLogin && !$store.state.isLogin) {
                next({
                    path: '/login'
                })
            } else {
                next()
            }
        }
 

组件内的守卫有三个,分别是:

  • beforeRouteEnter

  • beforeRouteUpdate

  • beforeRouteLeave

(1) beforeRouteEnter

可以在路由组件内直接定义以下路由导航守卫:
    在渲染该组件的对应路由被 confirm 前调用
    不!能!获取组件实例 this,因为当守卫执行前,组件实例还没被创建
    可以通过 next 获取data中的数据

  data() {
    return {
      name: "Grayly"
    };
  },  
  beforeRouteEnter: (to, from, next) => {
    next(vm => {
      alert("hello" + vm.name);
    })
  },
 

(2)  beforeRouteUpdate

这个方法是vue-router 2.2版本加上的。因为原来的版本中,如果一个在两个子路由之间跳转,是不触发beforeRouteLeave的。这会导致某些重置操作,没地方触发。在之前,我们都是用watch 的。但是通过这个勾子,我们有了更好的方式。

  beforeRouteUpdate (to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
  },
 

(3)beforeRouteLeave

这个离开守卫通常用来禁止用户在还未保存修改前突然离开。该导航可以通过 next(false) 来取消。
可以访问组件实例 this
  beforeRouteLeave: (to, from, next) => {
    if (confirm("你确定要离开吗") == true) {
      next();
    } else {
      next(false);
    }
  },
 

返回上一级路由

      第一种:history.back();
 
      第二种:this.$router.go(-1);

标签:Vue,beforeEach,next,守卫,router,组件,Router,路由
来源: https://blog.csdn.net/weixin_58206976/article/details/121190669