vue3之动态路由

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

在这里插入图片描述

修改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);
    }
    });
    };

这里要注意的是,设置component一定要用 import.meta.glob

到这里我们的动态路由已经拼好了,但是页面路由跳转之后白屏,官方文档给的是return to.fullPath,试了无效。所以我在动态路由设置好之后执行一下router.push(to.fullPath);就可以跳转页面啦

猜你喜欢

转载自blog.csdn.net/weixin_42255789/article/details/126986241
今日推荐