通俗易懂的谈谈 路由导航守卫

路由导航守卫

router.beforeEach

router.afterEach

router.beforeResolve

beforeEnter

beforeRouteEnter

beforeRouteUpdate (2.2 新增)

beforeRouteLeave

1.全局前置守卫----router.beforeEach

router.beforeEach 注册一个全局前置守卫:

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

router.beforeEach((to, from, next) => {
  //  to:要去哪个页面
  //  from:从哪里来
  //  next:它是一个函数。
  //     如果直接放行 next()
  //     如果要跳到其它页 next(其它页)
})

示例代码:

router.beforeEach(async(to, from, next) => {
  NProgress.start() // 开启进度条
  const token = store.state.user.token
  const userId = store.state.user.userInfo.userId
  console.log(token, to.path, from.path)
  if (token) {
    if (to.path === '/login') { // 有 token还要去login
      next('/')
      NProgress.done() // 关闭进度条
    } else { // 有 token,去其他页面,放行
      if (!userId) {
        await store.dispatch('user/getUserInfo')
      }
      next()
    }
  } else {
    if (to.path === '/login') { // 没有token,去login,放行
      next()
    } else {
      next('/login') // 没有token,去其他页面
      NProgress.done()
    }
  }
})

小结

  • router.beforeEach(回调(三个参数))
  • 导航守卫函数中,一定要调用next( )
  • to.path: to是一个路由对象,path表示路径,是它的一个属性

2. 全局后置钩子----router.afterEach

router.afterEach 注册一个全局后置钩子:

你也可以注册全局后置钩子,然而和守卫不同的是,这些钩子不会接受 next 函数也不会改变导航本身:

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

3. 全局解析守卫----router.beforeResolve

在 2.5.0+ 你可以用 router.beforeResolve 注册一个全局守卫。这和 router.beforeEach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。

4.路由独享的守卫

你可以在路由配置上直接定义 beforeEnter 守卫:

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

5.组件内的守卫

  • 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`
  }
}

完整的导航解析流程

  1. 导航被触发。
  2. 在失活的组件里调用 beforeRouteLeave 守卫。
  3. 调用全局的 beforeEach 守卫。
  4. 在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
  5. 在路由配置里调用 beforeEnter。
  6. 解析异步路由组件。
  7. 在被激活的组件里调用 beforeRouteEnter。
  8. 调用全局的 beforeResolve 守卫 (2.5+)。
  9. 导航被确认。
  10. 调用全局的 afterEach 钩子。
  11. 触发 DOM 更新。
  12. 调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值