Vue路由守卫

184 阅读2分钟

1. 全局前置守卫

  • 三个参数

    • to 即将进入的目标路由对象

    • from 当前导航即将离开的路由对象

    • next:functiotn

      • next() 进行管道中的下一个钩子
      • next(false) 中断当前导航
      • nuxt('/') 进入根路径
      • next(error) : 终止且该错误会被传递给 router.onError() 注册过的回调。
  • 确保 next 函数在任何给定的导航守卫中都被严格调用一次。它可以出现多于一次

  • 但是只能在所有的逻辑路径都不重叠的情况下,否则钩子永远都不会被解析或报错

router.beforeEach((to , from , next ) => {
  //进入登录页 没有限制
  if(to.path === '/login'){
    next();
    return
  }
  // 当需要登录检验的页面时
  if(!to.meta.auth){
    // 请求登录状态
    Http.loginState().then(res =>{
      if (res.code === 'SUCCESS'){
        // 如果为登陆状态执行预进入的路由
        next()
      }else {
        // 否则 弹窗提示进入登录页
        MessageBox.alert('您还未登录哦!', {
          showClose: false,
          type: 'warning',
          center: true,
          callback: () => {
            router.push({
              path: '/'
            })
          }
        })
      }
    })
  }else {
    next()
  }
  next()
})

2. 全局后置钩子

  • 不会接受next钩子
router.afterEach((to, from) => {
  // ...
})

3. 路由独享的守卫

  • 路由配置上直接定义
  • 一定要记住有next()
const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Login,
      beforeEnter: (to, from, next) => {
            next();
      }
    }
  ]
})

4. 组件内的守卫

  • beforeRouteEnter

    • 不可以访问this
    • 你可以通过传一个回调vmnext来访问组件实例。在导航被确认的时候执行回调,并且把组件实例作为回调方法的参数。
    • beforeRouteEnter (to, from, next) {
        next(vm => {
          // 通过 `vm` 访问组件实例
        })
      }
      
  • beforeRouteUpdate

  • beforeRouteLeave

    • 常见用法: 退出界面是是否保存修改
    • beforeRouteLeave (to, from, next) {
        const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
        if (answer) {
          next()
        } else {
          next(false)
        }
      }
      
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`
  }
}

\