vue 路由守卫,更好的封装和使用拦截 -戴向天

大家好!我叫戴向天

QQ群:602504799

如若有不理解的,可加QQ群进行咨询了解

/**
 * beforeMehodMap
 * 主要是做多个守卫处理
 * 每一个方法返回的不是true 就是 重定向的地址
 */
const beforeMehodMap: any = {
  /**
   * 判断有没有相对应的地址 若是没有就进行跳转404页面
   */
  notFound(to: any, from: any) {
    const pathMap = getAllRouterPaths(
      (router as any).options.routes as IRouterChildren[],
    );
    return pathMap.indexOf(to.path) > -1 ? true : '/404';
  },
  /**
   * 判断用户有没有登录,登录成功后就不允许再进入登录界面,否则直接返回到首页
   */
  isLogin(to: any, from: any) {
    const username = Storage.get('username');
    if (username) {
      if (to.path === '/login') {
        return '/';
      } else {
        return true;
      }
    } else if (to.path === '/login') {
      return true;
    } else {
      return '/login';
    }
  },
  rootJudge(to: any, from: any) {
    if (
      rootPath.length <= 0 ||
      ['/login', '/403', '/404'].indexOf(to.path) >= 0
    ) {
      return true;
    }
    const isFullPath = rootPath.indexOf(to.path) >= 0;
    if (isFullPath) {
      return true;
    }
    let splitPath = to.path.split('/');
    splitPath = splitPath.slice(0, splitPath.length - 1).join('/');
    console.log('splitPath=>', splitPath);
    const splitMatching = rootPath.some((path: string) => {
      const itemPath = path.split('/');
      const rigthPath = itemPath.slice(0, itemPath.length - 1).join('/');
      return rigthPath === splitPath;
    });
    if (splitMatching) {
      return true;
    } else {
      return '/403';
    }
  },
};

/**
 * author 戴向天
 * 路由守卫 - 处理
 */
router.beforeEach((to: any, from: any, next: any) => {
  const methods = Object.keys(beforeMehodMap);
  const len = methods.length;
  for (let i = 0; i < len; i++) {
    const key = methods[i];
    if (typeof beforeMehodMap[key] === 'function') {
      const res = beforeMehodMap[key](to, from);
      if (res !== true) {
        return next({ path: res, replace: true });
      }
    }
  }
  next();
});

// 获取所有路由
function getAllRouterPaths(
  arr: IRouterChildren[],
  before: string = '',
): string[] {
  let pathMap: string[] = [];

  arr.forEach((routerChilren: IRouterChildren) => {
    const path = (before === '/'
      ? routerChilren.path
      : before + routerChilren.path
    ).replace(/\/+/g, '/');
    pathMap.push(path);
    if (routerChilren.children && routerChilren.children.length) {
      pathMap = pathMap.concat(
        getAllRouterPaths(routerChilren.children, path + '/'),
      );
    }
  });

  return pathMap;
}

猜你喜欢

转载自blog.csdn.net/weixin_41088946/article/details/114403836