本文最后更新于 2024-11-26 17:46:05
根据目录自动生成路由
关键字:import.meta.glob
常用的路由配置方式已经满足使用,但是为了追求更好的路由配置方式,减少繁琐的配置方式,可以将路由和文件夹关联起来
- 使用此方法可以让路由随着文件夹的创建而创建(根据微信小程序开发的思想,注意,每个文件夹下必须有一个
.vue
和.js
文件,而且名字必须一致,生成的路由就是改名字的路由)
- 例如:在
views
下(因为以下的代码是由views
目录下的文件产生的路由),
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| - views - index - index.vue - index.js - second - second.vue - second.js
- views - index - index.vue - index.js - son - son.vue - son.js - second - second.vue - second.js
export default { meta: { title: '通知' } }
JS
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| const pages = import.meta.glob('../views/**/*.js', { eager: true, import:'default' });
const components = import.meta.glob('../views/**/*.vue');
const routes = Object.entries(pages).map(([path, mate]) => { const pathRealy = path.replace('../views', '').replace(/\/[^/]*\.js$/, '') || '/'; const nameRealy = path.split('/').pop().replace('.js', ''); const componentRealy = components[path.replace('.js', '.vue')]; return { path: pathRealy, name: nameRealy, component: componentRealy, meta: mate.meta } });
const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: routes })
router.beforeEach((to, from, next) => {
if (to.path == '/') { next('/first'); return; } nextTick(() => { if (to.meta.title) { document.title = to.meta.title; } else { document.title = '默认标题'; } }); next(); });
JS
|
看了上面这多代码,的确比较难懂,其实在自己调试的手可以打印出来,看看每一步处理的什么东西