Router
介绍
工程中的Router会根据src/views
目录结构自动生成路由配置,路由结构与文件系统结构保持一致,不需要手动编写routes = [...]
,使得项目结构更加直观和易于理解。
配置
配置文件:
router
└─ index.ts
import {
createRouter, createWebHistory, RouteRecordRaw} from "vue-router";
const ps = import.meta.glob("../views/**/page.ts", {
eager: true, import: 'default'})
const cs = import.meta.glob("../views/**/index.vue")
const re: string[] = []
function createChildRoutes(basePath: string): RouteRecordRaw[] {
const pObjs = Object.entries(ps)
const routes: RouteRecordRaw[] = pObjs.filter(([path]) => {
return path.startsWith(basePath) && path.split('/').length === basePath.split('/').length + 1;
}).map(([path, params]) => {
return createRoutes(path, params, (path) => {
path = path.replace('../views', '').replace('/page.ts', '').replace('[', ':').replace(']', '')
const name = path.replace(':', '').split('/').filter(Boolean).join('-') || 'index'
const pathArr = path.split('/')
const routePath = pathArr[pathArr.length - 1]
re.push(name)
return [routePath, name