【Vue3+Vite】使用 glob 生成动态路由

约定大于配置

在工程化项目中,约定大于配置能节省很多重复代码的编写,故先约定视图的创建规范:

  1. 首页放在 views/index.vue 路径中。

  2. 当需要新建视图时,以视图名创建一个目录,例如 views/resource-link(视图名遵循短横杠法),再在目录下新建 index.vue 文件当作视图。

  3. 参考小程序的做法,对应地在每个同级 index.vue 下新建 page.ts 文件,用来配置路由的 meta,例如:

    export default {
      title: '主页'
    }
    

短横杠命名法:单词首字母小写,单词之间以短横杠分隔。

目录结构参考图

目录结构

router.ts

Vue Router 的配置代码如下,复制即可:

import { createRouter } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const pageModules = import.meta.glob('../views/**/page.ts', {
	eager: true,
	import: 'default'
})
const componentModules = import.meta.glob('../views/**/index.vue', {
	eager: true,
	import: 'default'
})
const routes = Object.entries(pageModules).map(([pagePath, config]) => {
	const path = pagePath.replace('../views', '').replace('/page.ts', '') || '/'
	const name = path.split('/').filter(Boolean).join('-') || 'index'
	const compoentPath = pagePath.replace('page.ts', 'index.vue')
	return {
		path,
		name,
		component: componentModules[compoentPath],
		meta: config
	}
})

const routeMap: Map<string, RouteRecordRaw> = new Map()
routes.forEach((route: any) => {
	const title = route.meta.title
	routeMap.set(title, route)
})

const router = createRouter({
	// ...
	routes: Array.from(routeMap.values())
})

router.beforeEach(async (to, from, next) => {
	const baseTitle = '网站名'
	if (to.meta.title) {
		document.title = `${to.meta.title} - ${baseTitle}`
	} else {
		document.title = baseTitle
	}
	// ...
	next()
})

export default router

// 在其他组件中需要跳转视图时,通过 getpath(title) 来动态获取 path,例如 getpath('登录')
export const getPath = (title: string): string => {
	return routeMap.get(title)?.path || '/'
}

参考资料

[1] 渡一机构. 在vite中使用glob完成自动化导入【渡一教育】[Z/OL]. https://www.bilibili.com/video/BV1xw411K7Zz. 2023.

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值