109  
查询码:00001078
vue3之动态路由
作者: 徐文彬 于 2022年09月22日 发布在分类 / 人防组 / 人防前端 下,并于 2022年09月22日 编辑

后端返回的数据结构如下图

粘贴图片

修改router的index.ts文件

menus为拿到的数据,在setRoutes方法中组装路由


方法代码

/**

设置动态路由
@param menus 接口菜单数据
@param parentName 父级路由名称
@param parentPath 父级路由路径
/
const components = import.meta.glob("@/views/**/.vue");
const layouts = import.meta.glob(“@/layout/**/*.vue”);
const setRoutes = (menus: any, parentName?: any, parentPath?: any) => {
menus.forEach((menu: any) => {
const route: any = {};
route.path = parentPath ? ${parentPath}/${menu.route} : /${menu.route};
if (menu.path === “null”) {
route.name = parentName;
} else {
if (menu.path.includes(“layout/”)) {
router.addRoute({
path: “/”,
name: “layout-” + menu.route,
component: () => import(“@/layout/index.vue”)
});
route.name = menu.route;
route.component = components[../${menu.path.split("layout/")[1]}.vue];
router.addRoute(“layout-” + route.name, route);
} else {
route.name = menu.route;
if (menu.path == “layout”) {
route.component = layouts[../${menu.path}/index.vue];
router.addRoute(route);
} else {
route.component = components[../${menu.path}.vue];
router.addRoute(parentName, route);
}
}
}
if (menu.sonMenus.length > 0) {
// console.log(route.name, route.path);
setRoutes(menu.sonMenus, route.name, route.path);
}

});

};

注意

1、设置component一定要用 import.meta.glob

2、到这里动态路由已经拼好了,但是页面路由跳转之后白屏,官方文档给的是return to.fullPath,试了无效。这里的处理方法是在动态路由设置好之后再执行一下router.push(to.fullPath)。



有更好的处理方法,欢迎指导哦



 推荐知识

 历史版本

修改日期 修改人 备注
2022-09-22 17:54:17[当前版本] 徐文彬 20220922

 附件

附件类型

PNGPNG

  目录
    知识分享平台 -V 4.8.7 -wcp