vue 路由守卫

作者: 暴躁程序员 | 来源:发表于2022-01-15 17:40 被阅读0次

    参考官网: https://router.vuejs.org/zh/guide

    • 路由守卫种类:三大全局路由守卫,三大组件路由守卫,一个路由独享守卫
    • 使用位置:全局和独享在路由文件 src\router\index.js,组件守卫在组件中
    • 相关参数
      to :要跳转到的目标路由信息
      from:跳转前的路由信息
      next():不传参执行下一步,传false阻断程序执行,传 { path: '路径' } 或者 { name: "Login" } 跳转到目标路由

    1. 三大全局路由守卫

    全局守卫使用前需要修改下路由文件,否则就得拿到 main.js 中配置全局守卫
    使用全局守卫必须获取路由实例化对象

    const routes = []  // 路由对象在此配置
    const router = new Router({
      routes
    });
    
    /******** 在此区域配置路由全局守卫 **********/
    
    export default router;
    

    全局路由守卫先执行,组件生命周期后执行
    使用位置:路由文件 src\router\index.js

    // 全局前置守卫
    // 在页面加载之前执行,在所有守卫和生命周期之前执行,优先级第一
    // 不使用 next()方法 会阻断程序
    router.beforeEach((to, from, next) => {
      console.log("beforeEach", to, from);
    
      to.meta.requireAuth = false;
       //判断该路由是否需要登录权限
      if (to.meta.requireAuth) {
        if (cookies("token")) {
          next();
        } else {
          next({
            path: "/login",
            query: { redirect: to.fullPath } 
            // 保存要跳转的目标路由,登录成功后跳转到该路由
          });
        }
      } else {
        next();
      }
    });
    
    // 全局解析守卫
    // 在beforeEach之后执行
    // 不使用 next()方法 会阻断程序
    router.beforeResolve((to, from, next) => {
      console.log("beforeResolve", to, from);
      next();
    });
    
    // 全局后置守卫
    // 在beforeResolve之后执行
    // 没有next()
    router.afterEach((to, from) => {
      console.log("afterEach", to, from);
    });
    

    2. 一大路由独享守卫

    使用位置:路由文件 src\router\index.js 路由对象中

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

    3. 三大组件内守卫

    在组件中使用

    // 进入组件时执行
    // 不!能!获取组件实例 `this`
    beforeRouteEnter (to, from, next) {
      console.log("beforeRouteEnter ", to, from);
      next();
    },
    // 在当前路由改变,但是该组件被复用时调用
    // 可以访问组件实例 `this`
    beforeRouteUpdate (to, from, next) {
      console.log("beforeRouteUpdate ", to, from);
      next();
    },
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    beforeRouteLeave (to, from, next) {
      console.log("beforeRouteLeave ", to, from);
      next();
    },
    

    4. 路由守卫执行的先后顺序

    导航被触发。
    在失活的组件里调用 beforeRouteLeave 守卫。
    调用全局的 beforeEach 守卫。
    在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
    在路由配置里调用 beforeEnter。
    解析异步路由组件。
    在被激活的组件里调用 beforeRouteEnter。
    调用全局的 beforeResolve 守卫 (2.5+)。
    导航被确认。
    调用全局的 afterEach 钩子。
    触发 DOM 更新。
    调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。
    

    相关文章

      网友评论

        本文标题:vue 路由守卫

        本文链接:https://www.haomeiwen.com/subject/fsbwcrtx.html