Vue路由动态加载
Posted tylz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue路由动态加载相关的知识,希望对你有一定的参考价值。
首先新建vue工程,一般我们不会特殊处理路由,但当项目页面越来越多,路由配置也会越来越大,路由文件就会变得不好维护
import Vue from ‘vue‘ import Router from ‘vue-router‘ import HelloWorld from ‘@/components/HelloWorld‘ import Home from ‘@/components/Home‘ import Test1 from ‘./test1.router.js‘ import Test2 from ‘@/components/children/Test2‘ import Test3 from ‘@/components/children/Test3‘ Vue.use(Router) export default new Router( routes: [ path: ‘/HelloWorld‘, name: ‘HelloWorld‘, component: HelloWorld , path:‘/‘, name:‘Home‘, component:Home, children:[ path:‘/test2‘, name:‘Test2‘, component:Test2, , path:‘/test3‘, name:‘Test3‘, component:Test3, ] ] )
这是一个很简单的路由文件,我们先进性第一步优化,按一级菜单分类:
新建test1.router.js文件,放置一级菜单test1下的所有路由信息
export default path:‘/test1‘, name:‘test1‘, component: () => import(‘@/components/children/Test1‘), children:[]
component: () => import(‘@/components/children/Test1‘)这个是配置路由懒加载,优化首屏加载缓慢
在index.js里引入该文件
import Vue from ‘vue‘ import Router from ‘vue-router‘ import HelloWorld from ‘@/components/HelloWorld‘ import Home from ‘@/components/Home‘ import Test1 from ‘./test1.router.js‘ import Test2 from ‘./test2.router.js‘ import Test3 from ‘./test3.router.js‘ Vue.use(Router) export default new Router( routes: [ path: ‘/HelloWorld‘, name: ‘HelloWorld‘, component: HelloWorld , path:‘/‘, name:‘Home‘, component:Home, children:[ Test1, Test2, Test3 ] ] )
做到这块,已经可以满足很多项目了,路由文件已经很清晰了,但当项目较大,依然会不清晰
import Vue from ‘vue‘ import Router from ‘vue-router‘ import Home from ‘@/components/Home‘ Vue.use(Router) let routers = []; let getALLRouterMsg = (paths) => paths.keys().forEach( (key) => routers.push(paths(key).default) ) getALLRouterMsg(require.context(‘.‘,true,/\.router\.js/)) export default new Router( routes: [ path:‘/‘, name:‘Home‘, component:Home, children:[ ...routers ] ] )
以上是关于Vue路由动态加载的主要内容,如果未能解决你的问题,请参考以下文章