当前位置: 首页 > news >正文

用vite动态导入vue的路由配置

        在Vue应用中,通过路由可以实现不同页面之间的切换,同时也可以实现页面之间的传参和控制页面的显示与隐藏。但是我们在开发的过程中,会发现在路由配置中的路由配置和我们的项目结构高度重复,在我们修改页面文件结构时非常的麻烦与复杂,这时候,如果可以动态的导入路由,就可以大大提示我们项目的可维护性。

        我们在开发中会经常听见一句话,约定大于配置,路由的动态导入也是这句话应用的一种,我们这里动态导入路由模仿了在uniapp进行小程序开发的页面配置文件,要求有以下几点:

  1. 所有的页面都必须配置到/src/pages文件夹下;
  2. 所有的页面文件层级必须是/src/pages/页面文件夹名称/;
  3. 所有的页面文件中必须有page.ts作为配置文件和index.vue作为页面入口文件;

结构展示如下:

page.ts文件展示:

//home的page.ts
export default {title: '首页',menuOrder: 1,childrens: [`../pages/homechildren`]
}
//homechildren的page.ts
export default {title: '首页的子组件',menuOrder: 1,isChild: true,
}
//login的page.ts
export default {title: '登录',menuOrder: 2
}

        此时我们要通过vite的函数import.meta.glob()和import()扫描pages文件夹动态生成路由,代码如下:

//路由配置文件
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'const pages = import.meta.glob('../pages/**/page.ts', {eager: true,import: 'default'
})const components = import.meta.glob('../pages/**/index.vue')const getChildRoutes = async (childrens: string[]) => {const res = [];for (const item of childrens) {const pageModule = await import(`${item}/page.ts`);const componentModule = await import(`${item}/index.vue`);const routePath = item.replace('../pages/', '').replace('/page.ts', '') || '/';const name = routePath.split('/').filter(Boolean).join('-') || 'index';res.push({path: routePath,name,component: componentModule.default,meta: pageModule.default});}return res;
};const routes = Object.entries(pages).filter(([path, meta]: [string, any]) => !meta.isChild).map(([path, meta]: [string, any]) => {const compPath = path.replace('page.ts', 'index.vue')path = path.replace('../pages', '').replace('/page.ts', '') || '/';const name = path.split('/').filter(Boolean).join('-') || 'index';return {path,name,component: components[compPath],meta: meta,children: !!meta.childrens ? getChildRoutes(meta.childrens) : []} as RouteRecordRaw
})const router = createRouter({history: createWebHistory(),routes: routes,
})//路由重定向
router.beforeEach((to, from, next) => {if (to.path === '/') {next('/home')} else if (!routes.some(route => route.path === to.path)) {next('/home')} else {next()}})export {router
}

 效果展示:

路由对象展示:

相关文章:

  • 递归、搜索和回溯算法《递归》
  • 飞凌嵌入式T527核心板获得【OpenHarmony生态产品兼容性证书】
  • window 图形显示驱动-在 WDDM 1.2 中提供无缝状态转换(下)
  • 关于健身房管理系统前后端软件开发主要功能需求分析
  • 《Astro 3.0岛屿架构让内容网站“脱胎换骨”》
  • RISCV学习(5)GD32VF103 MCU架构了解
  • 【AI News | 20250428】每日AI进展
  • transformer-实现单层encoder_layer
  • VINS-FUSION:跑通手机录制数据
  • C语言----操作符详解(万字详解)
  • 4月28日日记
  • 待验证---Oracle 19c 在 CentOS 7 上的快速安装部署指南
  • C#与SVN的深度集成:实现版本控制自动化管理​
  • MATLAB实现神经网络的OCR识别
  • Web 基础与 HTTP 协议
  • STM32的SysTick
  • 学成在线。。。
  • 【爬虫】码上爬第2题:headersi请求头验证
  • 排序算法详解笔记
  • 详解UnityWebRequest类
  • 长三角铁路“五一”假期运输今启动:预计发送旅客量增6%,5月1日当天有望创新高
  • 王毅会见俄罗斯外长拉夫罗夫
  • 全国电影工作会:聚焦扩大电影国际交流合作,提升全球影响力
  • 第二十届中国电影华表奖揭晓!完整获奖名单来了
  • 多地征集农村假冒伪劣食品违法线索,全链条整治“三无”产品
  • 证监会发布上市公司信披豁免规定:明确两类豁免范围、规定三种豁免方式