当前位置: 首页 > 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
}

 效果展示:

路由对象展示:

http://www.xdnf.cn/news/198667.html

相关文章:

  • 本地部署Qwen-7B实战 vLLM加速推理
  • 网络协议之为什么要分层
  • 论文分享 | 基于区块链和签名的去中心化跨域认证方案
  • 受限字符+环境变量RCE
  • vue3:v-model的原理示例
  • python练习:求数字的阶乘
  • 思科bsp社招面试
  • JavaScript 与 Java 学习笔记
  • day9 python 热力图与子图的绘制
  • MYSQL——时间字段映射Java类型
  • 庙算兵棋推演AI开发初探(7-神经网络训练与评估概述)
  • FTP-网络文件服务器
  • 使用 Vue3 + Webpack 和 Vue3 + Vite 实现微前端架构(基于 Qiankun)
  • iVX 图形化编程如何改写后端开发新范式
  • EXCEL中跨行匹配两组数据
  • 流域生态系统碳排放、碳循环模拟与评估技术应用
  • 【基础篇】static_config采集配置详解
  • Vue 3 中通过 createApp 创建的 app 实例的所有核心方法,包含完整示例、使用说明及对比表格
  • 深入解析 PyTorch 中的 torch.distributions模块与 Categorical分布
  • 2025吃鸡变声器软件推荐
  • 【Vue3 组合式 API 在大型项目中的实践:useOperatorData 封装与应用】
  • 如何开发动态贴纸功能?一体化美颜SDK的技术实现思路与实战方案
  • Java 入门宝典--注释、关键字、数据类型、变量常量、类型转换
  • 服务器部署,Nginx安装和配置
  • 思维链理解汇总
  • 美团社招一面
  • 2025天津二类医疗器械经营备案攻略
  • AI 边缘盒子:智能与效率的边缘先锋
  • 生成对抗网络(Generative Adversarial Nets,GAN)
  • 知识付费平台推荐及对比介绍