Vue导航守卫

什么是导航守卫?

在vue路由的需求中,经常有这样的一种情况,就是每当进行路由跳转时,我需要预先进行一些判断,做一些事情,这时候你就需要Vue的导航守卫了!

1、router.beforeEach

注册一个全局前置守卫

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

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

2、router.afterEach

全局后置钩子

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

3、beforeEnter路由独享的守卫

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

4、组件内的守卫

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

使用示例

router.beforeEach((to, from, next) => {
  // ...
  console.log('to',to);
  console.log('from',from);

  next(true);
});
router.afterEach((to, from) => {
  // ...
  if(from.fullPath == '/loginRegister'){
    //alert('页面信息保存成功!');
  }
});

猜你喜欢

转载自blog.csdn.net/mapbar_front/article/details/80115151