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;