Vue3+ts根据views目录文件自动生成路由

Vue3+ts根据views目录文件自动生成路由

新建 router.ts在src目录
main,ts中引入
import router from “./router”;

import { createApp } from 'vue'
import App from './App.vue'
import router from "./router";

const app = createApp(App)
app.use(router);
app.mount('#app')

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

const handler = (str: string) => {

    let arr = str.split(`/`);
    let newArr = arr.map((ele, idx) => {
        return idx === 0 ? ele : ele[0].toUpperCase() + ele.slice(1);
    })
    return newArr.join(``);
}
const modules = import.meta.glob('./views/*.vue');
const modulesList: any[] = [];
const layout: string = "layout.vue"
if (!Object.hasOwnProperty.call(modules, `./views/${layout}`)) {
    modulesList.push({
        name: 'Index',
        path: '/',
        component: () => import("./views/index.vue")
    });
    Object.keys(modules).forEach((path: any) => {
        const name = path.substring(7).replace(".vue", "");
        modulesList.push({
            name,
            path: name,
            component: modules[path]
        });
    })
} else {
    const modulesIndex: any[] = [{
        name: 'Index',
        path: '/',
        component: () => import("./views/index.vue")
    }];

    Object.keys(modules).forEach((path: any) => {
        if (path !== `./views/${layout}`) {
            const name = path.substring(7).replace(".vue", "");
            modulesIndex.push({
                name,
                path: name,
                component: modules[path]
            });
        }
    })
    modulesList.push({
        name: 'Index',
        path: '/',
        component: () => import(`./views/${layout}`),
        children: modulesIndex
    })
}


const modulesSub = import.meta.glob('./views/*/*.vue');
console.log(modulesSub);
const modulesSubList: any = {};
Object.keys(modulesSub).forEach((path: any) => {
    const namePath = path.substring(7).replace(".vue", "");
    const nameArray = namePath.split('/');
    const name = handler(namePath);
    if (!Object.hasOwnProperty.call(modulesSubList, name[1])) {

        if (Object.hasOwnProperty.call(modulesSub, `./views/${nameArray[1]}/${layout}`)) {
            modulesSubList[name[1]] = {
                name: `${nameArray[1]}Index`,
                path: `/${nameArray[1]}`,
                component: modulesSub[`./views/${nameArray[1]}/${layout}`],
                children: [{
                    name: `${nameArray[1]}Index`,
                    path: `/${nameArray[1]}`,
                    component: modulesSub[`./views/${nameArray[1]}/index.vue`]
                }]
            };
        } else {
            modulesSubList[name[1]] = {
                name: `${nameArray[1]}Index`,
                path: `/${nameArray[1]}`,
                component: modulesSub[path],
                children: []
            };
        }
    }
    if (path !== `./views/${nameArray[1]}/${layout}`) {
        modulesSubList[name[1]].children.push({
            name,
            path: namePath,
            component: modulesSub[path]
        });
    }
})

Object.keys(modulesSubList).forEach((path: any) => {
    modulesList.push(modulesSubList[path]);
})

modulesList.push({
    path: '/:pathMatch(.*)*',
    name: 'notFound',
    component: () => import('./views/404.vue'),
});
const router = createRouter({
    history: createWebHashHistory('/'),
    routes: modulesList,
});


export default router;



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_42945182

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值