一秒教你搞定前端打包上传后路由404的问题!

1、问题描述

前端实现权限管理后,本地路由跳转正常,打包上传线上出现前404找不到路由路径问题

报如下错误:

 2、错误原因

打包之后根路径变化,前端没有将获取到的用户菜单权限中的component进行转换,导致上传后路径错误

3、解决方法(基于Vue3+ts)

step1:

在添加菜单时,不写component的前缀,比如原本前端控制路由时的写法: ×

component: () => import('/@/views/home/index.vue')   或

component: () => import('/@/layout/routerView/parent.vue')

实际添加时,component的正确写法如下:

/home/index.vue   或

/layout/routerView/parent.vue

step2:

在前置路由导航守卫中获取用户的权限后,先获取目录下的 .vue、.tsx 全部文件

/**
 * 获取目录下的 .vue、.tsx 全部文件
 * @method import.meta.glob
 * @link 参考:https://cn.vitejs.dev/guide/features.html#json
 */
const layouModules: any = import.meta.glob('../layout/routerView/*.{vue,tsx}');
const viewsModules: any = import.meta.glob('../views/**/*.{vue,tsx}');
const dynamicViewsModules: Record<string, Function> = Object.assign({}, { ...layouModules }, { ...viewsModules });

再遍历菜单权限,将component的值进行转换

/**
 * 后端路由 component 转换
 * @param routes 后端返回的路由表数组
 * @returns 返回处理成函数后的 component
 */
export function backEndComponent(routes: any) {
  if (!routes) return;
  return routes.map((item: any) => {
    if (item.component) item.component = dynamicImport(dynamicViewsModules, item.component as string);
    item.children && backEndComponent(item.children);
    return item;
  });
}

/**
 * 后端路由 component 转换函数
 * @param dynamicViewsModules 获取目录下的 .vue、.tsx 全部文件
 * @param component 当前要处理项 component
 * @returns 返回处理成函数后的 component
 */
export function dynamicImport(dynamicViewsModules: Record<string, Function>, component: string) {
  const keys = Object.keys(dynamicViewsModules);
  const matchKeys = keys.filter((key) => {
    const k = key.replace(/..\/views|../, '');
    return k.startsWith(`${component}`) || k.startsWith(`/${component}`);
  });
  if (matchKeys?.length === 1) {
    const matchKey = matchKeys[0];
    return dynamicViewsModules[matchKey];
  }
  if (matchKeys?.length > 1) {
    return false;
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_48082900/article/details/131247426
今日推荐