常规配置路由
我们在编写路由项时,以vue3为例,常常会配置成如下:
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: "/",
name: "index",
component: () => import('../views/index.vue'),
meta: { title: "首页", menuOrder: 1 }
},
{
path: "/about",
name: "about-index",
component: () => import('../views/about/index.vue'),
meta: { title: "关于", menuOrder: 10 }
},
{
path: "/contact",
name: "contact-index",
component: () => import('../views/contact/index.vue'),
meta: { title: "联系", menuOrder: 20 }
}
]
export const router = createRouter({
history: createWebHistory(),
routes
})
在配置vue-router时,这样的写法是绝大多数人常用的写法,如果页面数量较多会导致这个文件几百上千行,实际上多了很多的重复代码,于是我们能不能对这个代码进行优化?
用vite自动化生成路由
代码如下:
import { createRouter, createWebHistory } from 'vue-router'
const pages = import.meta.glob('../views/**/page.js', {
eager: true,
import: 'default'
})
const pageComps = import.meta.glob('../views/**/index.vue')
const routes = Object.entries(pages).map(([path, meta]) => {
const pageJSPath = path
path = path.replace('../views', "").replace('/page.js', "")
path = path || "/";
const name = path.split("/").filter(Boolean).join("-") || "index";
const compPath = pageJSPath.replace("page.js", "index.vue")
return {
path,
name,
component: pageComps[compPath],
meta
}
})
export const router = createRouter({
history: createWebHistory(),
routes
})
这样就实现了一个自动化生成路由。
值得注意的是,需要遵守好一定的规范:
- 页面需要在views里面新建,并且页面组件新建需要命名为index.vue
- 每个页面都有一个page.js文件,用来存放一些配置文件
如果是webpack构建的话,也可以通过require.context的方式实现相同的功能。
未完待续。。。