VueRouter进阶一(导航钩子和路由元信息)

导航钩子

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

全局钩子vue-router

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

const router = new VueRouter({ ... })

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

当一个导航触发时,全局的 before 钩子按照建立顺序调用。钩子是异步解析执行,此时导航在全部钩子 resolve 完以前一直处于 等待中。浏览器

每一个钩子方法接收三个参数:异步

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

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

next: Function: 必定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。

next(): 进行管道中的下一个钩子。若是所有钩子执行完了,则导航的状态就是 confirmed (确认的)。

next(false): 中断当前的导航。若是浏览器的 URL 改变了(多是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。

next('/') 或者 next({ path: '/' }): 跳转到一个不一样的地址。当前的导航被中断,而后进行一个新的导航。

确保要调用 next 方法,不然钩子就不会被 resolved。ui

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

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

你能够在路由配置上直接定义 beforeEnter 钩子:code

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

这些钩子与全局 before 钩子的方法参数是同样的。
组件内的钩子component

最后,你能够在路由组件内直接定义如下路由导航钩子:router

beforeRouteEnter
beforeRouteUpdate (2.2 新增)
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 钩子 不能 访问 this,由于钩子在导航确认前被调用,所以即将登场的新组件还没被建立。

不过,你能够经过传一个回调给 next来访问组件实例。在导航被确认的时候执行回调,而且把组件实例做为回调方法的参数。

beforeRouteEnter (to, from, next) {
  next(vm => {
    // 经过 `vm` 访问组件实例
  })
}

路由元信息

你能够 在 beforeRouteLeave 中直接访问 this。这个 leave 钩子一般用来禁止用户在还未保存修改前忽然离开。能够经过 next(false) 来取消导航。
定义路由的时候能够配置 meta 字段:

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      children: [
        {
          path: 'bar',
          component: Bar,
          // a meta field
          meta: { requiresAuth: true }
        }
      ]
    }
  ]
})

那么如何访问这个 meta 字段呢?

首先,咱们称呼 routes 配置中的每一个路由对象为 路由记录。路由记录能够是嵌套的,所以,当一个路由匹配成功后,他可能匹配多个路由记录

例如,根据上面的路由配置,/foo/bar 这个 URL 将会匹配父路由记录以及子路由记录。

一个路由匹配到的全部路由记录会暴露为 $route 对象(还有在导航钩子中的 route 对象)的 $route.matched 数组。所以,咱们须要遍历 $route.matched 来检查路由记录中的 meta 字段。

下面例子展现在全局导航钩子中检查 meta 字段:

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!auth.loggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next() // 确保必定要调用 next()
  }
})
相关文章
相关标签/搜索