Vue.js 路由钩子详解

Vue.js 李丽红
文章标签: vue.js

vue router路由钩子详解

导航钩子

正如其名,vue-router 提供的导航钩子主要用来拦截导航,让它完成跳转或取消。有多种方式可以在路由导航发生时执行钩子:全局的, 单个路由独享的, 或者组件级的。

全局钩子

你可以使用 router.beforeEach 注册一个全局的 before 钩子:

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


同样可以注册一个全局的 after 钩子,不过它不像 before 钩子那样,after 钩子没有 next 方法,不能改变导航

router.afterEach(route => { // ...})

某个路由独享的钩子

你可以在路由配置上直接定义 beforeEnter 钩子:

  1. const router = new VueRouter({
  2. routes: [
  3. {
  4. path: '/foo',
  5. component: Foo,
  6. beforeEnter: (to, from, next) => {
  7. // ...
  8. }
  9. }
  10. ]
  11. })

这些钩子与全局 before 钩子的方法参数是一样的。

组件内的钩子

最后,你可以在路由组件内直接定义以下路由导航钩子:

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

beforeRouteEnter 钩子 不能 访问 this,因为钩子在导航确认前被调用,因此即将登场的新组件还没被创建。

不过,你可以通过传一个回调给 next来访问组件实例。在导航被确认的时候执行回调,并且把组件实例作为回调方法的参数。

  1. beforeRouteEnter (to, from, next) {
  2. next(vm => {
  3. // 通过 `vm` 访问组件实例
  4. })
  5. }

你可以 在 beforeRouteLeave 中直接访问 this。这个 leave 钩子通常用来禁止用户在还未保存修改前突然离开。可以通过 next(false) 来取消导航。

还能输出{{restrictNumber}}个字符  
  • {{reply.author}}

    {{CommonUtil.formateDate(reply.ac_CommentDate).shortTime}}
  • 回复了{{Comments.author}} :