五 · 从零开始搭建一个项目(抽离路由做成动态组件并且绑定到顶部导航栏)

29 阅读1分钟

1.抽离理由成json文件

image.png

export interface RouterProps {
    path: string;
    name: string;
    component: string;
    meta?: {
        title: string;
        icon?: string;
        hidden?: boolean;
    };
    children?: RouterProps[];

}


export const layoutList: RouterProps[] = [
    {
        path: 'home',
        name: 'home',
        component: '/home/Home',
        meta: {
            title: '首页',
            icon: 'icon-home',
            hidden: false,
        },
    },
]

image.png

2.src -> 新建utils目录 -> routerUtil.ts (动态添加路由)

// 引入所有的views下面的vue文件
import type {RouterProps} from "../router/layoutList.ts";
import type {RouteRecordRaw} from "vue-router";

const modules = import.meta.glob('../views/**/*.vue');


export const createRouterList = (layoutList: RouterProps[]) => {
    console.log(modules)
    return layoutList.map((item: RouterProps) => {
        console.log(`../views${item.component}.vue`)
        const route = {
            path: item.path,
            name: item.name,
            meta: item.meta,
            component: modules[`../views${item.component}.vue`],
        } as RouteRecordRaw;
        if (item.children && item.children.length > 0) {
            route.children = createRouterList(item.children);
        }

        return route;
    });

};

image.png 3.将路由放进layout子路由里

image.png

4.改造Layout顶部导航栏

使用map将layoutList变成需要的格式 image.png 5.添加一天新的路由 views -> user -> User.vue

image.png 5.layoutList添加新的路由

image.png 6.运行项目

image.png