bug fix -- vue router 刷新白屏,以及死循环

1,180 阅读1分钟

下方的代码有问题的,具体表现是 刷新白屏, 或者 返回上一个网页(点击地址栏 前进后退按钮) 时,死循环

原因: next() 会跳出 beforeEach, 并且跳转到我们想去的组件,但是 next({ ...to, replace: true }); 不会,它会再次进入 beforeEach 这个函数, 然后 就会陷入死循环.

所以核心思路是 我们需要 在某种情形下让它不再进入 beforeEach 这个函数

router.beforeEach(async (to, from, next) => {
  const hasToken = getToken();
  console.log("hasToken", hasToken, to.path);
  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      
        router.addRoutes([...asyncRoutes]);
        store.commit("permission/SET_ROUTES", asyncRoutes);
        next({ ...to, replace: true });
      
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
  }
});

修改后代码如下所示

router.beforeEach(async (to, from, next) => {
  const hasToken = getToken();
  console.log("hasToken", hasToken, to.path);
  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      // 在这里加了逻辑判断
      if (store.getters.permission_routes.length) {
        next();
      } else {
        
        router.addRoutes([...asyncRoutes]);
        // 执行这个代码之后, store.getters.permission_routes.length  就是 true 了,因次可以调出死循环
        store.commit("permission/SET_ROUTES", asyncRoutes);
        next({ ...to, replace: true });
      }
      
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
  }
});

后记

这个是用的大佬写的模板项目vue-admin, 大佬实在是 tql ,膜拜. 我好菜...
一个相似的bug的解决方案