Vue大型应用路由拆分方案:将路由拆分为独立文件
当然可以!这其实是大型Vue项目中非常推荐的路由组织方式,能彻底解决你现在遇到的文件冗长、维护困难的问题。我来一步步给你拆解实现方案:
1. 拆分模块路由文件
首先在你的router目录下新建一个modules文件夹,然后给每个业务模块单独创建路由文件,比如router/modules/this.js、router/modules/that.js。每个文件只负责自己模块的组件导入和路由配置:
比如router/modules/this.js的内容:
// 只导入当前模块需要的组件 import This from '../../components/This' import ThisDetail from '../../components/ThisDetail' // 导出当前模块的路由数组 export default [ { path: '/this', name: 'This', component: This }, { path: '/this/detail/:id', name: 'ThisDetail', component: ThisDetail }, // 当前模块的其他路由都可以在这里添加 ]
再比如router/modules/that.js:
import That from '../../components/That' export default [ { path: '/that', name: 'That', component: That }, ]
2. 主路由文件整合所有模块
接下来修改router/index.js,把各个模块的路由导入并合并到主路由数组中,这样主文件会变得非常简洁:
import Vue from 'vue' import Router from 'vue-router' // 导入各个模块的路由 import thisRoutes from './modules/this' import thatRoutes from './modules/that' // 后续新增模块只需要在这里加一行导入即可 Vue.use(Router) export default new Router({ routes: [ // 可以保留全局通用路由,比如首页重定向、404页面 { path: '/', redirect: '/this' }, { path: '*', component: () => import('../components/NotFound') }, // 展开各个模块的路由数组 ...thisRoutes, ...thatRoutes, // 新增模块的路由在这里展开 ] })
3. 进阶优化:自动导入模块路由(可选)
如果你的模块特别多,每次新增模块都要手动导入会有点麻烦,这时候可以用Webpack的require.context来自动批量导入所有模块路由,一劳永逸:
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) // 自动扫描router/modules下所有.js文件 const moduleContext = require.context('./modules', false, /\.js$/) const allModuleRoutes = [] // 遍历所有匹配的文件,收集路由 moduleContext.keys().forEach(filePath => { const routes = moduleContext(filePath).default allModuleRoutes.push(...routes) }) export default new Router({ routes: [ { path: '/', redirect: '/this' }, { path: '*', component: () => import('../components/NotFound') }, ...allModuleRoutes ] })
额外小技巧
- 如果想给模块路由统一加前缀(比如
/this模块下的路由都以/this开头),可以在整合时给路由路径统一拼接前缀:...thisRoutes.map(route => ({ ...route, path: `/this${route.path}` })) - 注意避免不同模块的路由
path重复,否则会导致路由匹配冲突。
内容的提问来源于stack exchange,提问作者gthuo
相关产品推荐
相关产品推荐

