Vue Router - 钩子函数

参考文档:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html

全局钩子:beforeEach,afterEach

1.beforeEach

const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
  // ...
})

router.beforeEach有三个参数:to/from/next

  • to: 即将要进入的路由对象
  • from: 当前导航正要离开的路由
  • next: 是function,一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
    1)next(): 进行管道中的下一个钩子。
    2)next(false): 中断当前的导航。
    3)next(’/’) 或者 next({ path: ‘/’ }): 跳转到一个不同的地址。
    4)next(error): 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。

2.afterEach

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

单个路由钩子:beforeEnter

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

beforeEnter有三个参数:to/from/next
跟全局钩子beforeEnter方法参数是一样的

路由组件钩子:beforeRouteEnter,beforeRouteUpdate,beforeRouteLeave

const Foo = {
  template: `...`,
  beforeRouteEnter (to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
  },
  beforeRouteUpdate (to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
  },
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
  }
}

beforeRouteEnter,beforeRouteUpdate,beforeRouteLeave
都有三个参数:to/from/next

  • beforeRouteEnter:此钩子不能访问this,因为这钩子在导航确认前被调用,因此即将登场的新组件还没被创建。
    beforeRouteEnter 是支持给 next 传递回调的唯一守卫。

  • beforeRouteUpdate 和 beforeRouteLeave:不支持传递回调

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值