vue入门(四)动态导入路由Router

2022-07-06  本文已影响0人  走码人

路由分模块动态导入

环境:vue3

常规路由配置

router/index.js

import {createRouter, createWebHashHistory} from "vue-router";
import Home from "../views/Home.vue";

const routes = [
    {
        path: '/',
        redirect: '/dashboard'
    }, {
        path: "/",
        name: "Home",
        component: Home,
        children: [
            {
                path: "/dashboard",
                name: "dashboard",
                meta: {
                    title: '系统首页'
                },
                component: () => import ( /* webpackChunkName: "dashboard" */ "../views/Dashboard.vue")
            }, {
                path: "/table",
                name: "basetable",
                meta: {
                    title: '表格'
                },
                component: () => import ( /* webpackChunkName: "table" */ "../views/BaseTable.vue")
            }, 
        ]
    }, {
        path: "/login",
        name: "Login",
        meta: {
            title: '登录'
        },
        component: () => import ( /* webpackChunkName: "login" */ "../views/Login.vue")
    }
];

const router = createRouter({
    history: createWebHashHistory(),
    routes
});

export default router;

将路由按模块拆分

结构如下图


image.png

约定模块的路由文件命名规范:*.router.js

import {createRouter, createWebHashHistory} from "vue-router";

// 本语句导入指定目录下所有符合条件的文件
// 一定要和自己的路由信息配置文件的命名相符合,不然扫描不到
const routerFiles = import.meta.globEager('./modules/*.router.js')

//debugger
const routes  = []

// 将扫描到的路由信息加入路由数组中
for (const file in routerFiles) {
    //console.log("file->>>>>>",file)
    if (Object.prototype.hasOwnProperty.call(routerFiles, file)) {
        //子业务路由注册信息
        const subRoutes =routerFiles[file].default

        //遍历子模块的路由注册信息
        /* 方法1
        Object.entries(route).forEach(([index,value]) => {
            //console.log(index,value)
            routers.push(value)
        })*/
        //方法2
        for(let route of subRoutes) {
            //console.log(r)
            routes.push(r)
        }

    }
}

const router = createRouter({
    history: createWebHashHistory(),
    routes:routes
});

export default router;
上一篇 下一篇

猜你喜欢

热点阅读