vue导航守卫

339 阅读2分钟

在脚手架中,全局导航守卫定义在index.js中,写在const router下边

全局前置守卫beforeEach

router.beforeEach((to, from, next) => {
  if(to.path == '/b'){
    next({
        path:"/login"
    })
  }else{
    next();
  }
})
每个守卫方法接收三个参数:
  • to: Route: 即将要去的路由
  • from: Route: 当前要离开的路由
  • next: Function: 执行下一步操作。如果不调用next,路由就卡在这里了 不往下走了
与路由元信息配合使用

如果网站中有多个路由在进入之前都需要先进行判断,那么可以在注册路由组件的时候,给每一个路由加一个meta属性,这样在导航守卫中打印to,可以看到to上有一个meta属性,我们可以通过判断meta来判断是否直接进行next()

  const routes = [
    ....
   {path: '/center',
    name: 'center',
    component: () => import('../views/Center.vue'),
    meta: { requiresAuth: true }}
    ....
  ]
  
  const router = new VueRouter({
    routes,
  })
  router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    if (!localStorage.getItem('user')) {
      next({
        path: '/sign'
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

全局解析守卫beforeResolve

这个不重要,知道就行

全局后置钩子afterEach

  • 这个守卫没有next参数!!!
  • 因为当它触发的时候,路由已经由/a到/b了

路由独享守卫beforeEnter

  • 路由中自己单独使用的导航守卫
  • beforeEnter的效果等价于全局守卫中的beforeEach,只不过这个beforeEnter只能当前路由用
const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})

组件内守卫

  • beforeRouteEnter 它内部不能访问this!!
  • beforeRouteUpdate
  • beforeRouteLeave
  • beforeRouteEnter 是支持给 next 传递回调的唯一守卫
const Foo = {
  template: `...`,
  beforeRouteEnter (to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
    //因为它不能访问this,所以它支持给next传递一个回调来访问组件实例
     next(vm => {
        // 通过 `vm` 访问组件实例
     })
  },
  beforeRouteUpdate (to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
  },
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    //这个离开守卫通常用来禁止用户在还未保存修改前突然离开。该导航可以通过 next(false) 来取消。
  }
}