全局守卫

  1. beforeEach 全局前置守卫:跳转前触发,常用于登录验证等需要跳转前告知的情况;
    const router = new VueRouter({ ... })
    
    router.beforeEach((to, from, next) => {
      // ...
    })
    
  2. beforeResolve 在 beforeEach 之后触发:
  3. afterEach 全局后置钩子:少了一个参数 next();
    const router = new VueRouter({ ... })
    
    router.afterEach((to, from) => {
      // ...
    })
    

路由独享的守卫

在路由配置上直接定义 beforeEnter 守卫,和全局的 beforeEach 完全相同,如果都设置则在beforeEach 之后紧随执行;

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
          // ...
      }
    }
  ]
})

组件内的守卫

  1. beforeRouteEnter 守卫:不能访问组件实例 this,因为在 beforeCreate 生命周期前触发,如果要访问组件实例,需要传一个回调给 next,导航被确认时执行回调(mounted 之后,支持给 next 传递回调的唯一守卫);

    export default {
      data() {
        //...
      },
      beforeRouteEnter(to, from, next) {
        next(vm => {
          // 通过 `vm` 访问组件实例
        })
      }
    }
    
  2. beforeRouteUpdate 守卫:this 已经可以使用了,没必要在 next 中传递回调了(也不支持);

    export default {
      data() {
        //...
      },
      beforeRouteUpdate(to, from, next) {
        // 在当前路由改变,该组件被复用时调用,可以访问组件实例 `this`
        // 动态参数路径 /foo/:id,在/foo/1和/foo/2之间跳转,这个钩子就会被调用
      }
    }
    
  3. beforeRouteLeave 守卫:通常用来禁止用户在还未保存修改前突然离开,该导航可以通过 next(false) 来取消,this 已经可以使用了,没必要在 next 中传递回调了(也不支持);

    export default {
      data() {
        //...
      },
      beforeRouteLeave(to, from, next) {
        // 导航离开该组件的对应路由时调用,可以访问组件实例 `this`
      }
    }
    

回调参数列表

  1. to: Route: 即将要进入的目标 路由对象;

  2. from: Route: 当前导航正要离开的路由;

  3. next: Function: 一定要调用该方法来 resolve 这个钩子(否则会死循环);

    • next(): 进行管道中的下一个钩子;
    • next(false): 中断当前的导航;
    • next(‘/’) 或者 next({ path: ‘/’ }): 跳转到一个不同的地址,当前的导航被中断,然后进行一个新的导航,可以向 next 传递任意位置对象,且允许设置诸如 replace: true、name: ‘home’ 之类的选项以及任何用在 router-link 的 to prop 或 router.push 中的选项;
    • next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调;
打赏作者
您的打赏是我前进的动力
微信
支付宝
评论

中午好👏🏻,我是 ✍🏻   疯狂 codding 中...

粽子

这有关于前端开发的技术文档和你分享。

相信你可以在这里找到对你有用的知识和教程。

了解更多

目录

  1. 1. 全局守卫
  2. 2. 路由独享的守卫
  3. 3. 组件内的守卫
  4. 4. 回调参数列表