VUE路由动态加载实例代码讲解
首先新建vue工程,一般我们不会特殊处理路由,但当项目页面越来越多,路由配置也会越来越大,路由文件就会变得不好维护
importVuefrom'vue' importRouterfrom'vue-router' importHelloWorldfrom'@/components/HelloWorld' importHomefrom'@/components/Home' importTest1from'./test1.router.js' importTest2from'@/components/children/Test2' importTest3from'@/components/children/Test3' Vue.use(Router) exportdefaultnewRouter({ 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下的所有路由信息
exportdefault{ path:'/test1', name:'test1', component:()=>import('@/components/children/Test1'), children:[] }
component:()=>import('@/components/children/Test1')这个是配置路由懒加载,优化首屏加载缓慢
在index.js里引入该文件
importVuefrom'vue' importRouterfrom'vue-router' importHelloWorldfrom'@/components/HelloWorld' importHomefrom'@/components/Home' importTest1from'./test1.router.js' importTest2from'./test2.router.js' importTest3from'./test3.router.js' Vue.use(Router) exportdefaultnewRouter({ routes:[ { path:'/HelloWorld', name:'HelloWorld', component:HelloWorld }, { path:'/', name:'Home', component:Home, children:[ Test1, Test2, Test3 ] } ] })
做到这块,已经可以满足很多项目了,路由文件已经很清晰了,但当项目较大,依然会不清晰
importVuefrom'vue' importRouterfrom'vue-router' importHomefrom'@/components/Home' Vue.use(Router) letrouters=[]; letgetALLRouterMsg=(paths)=>{ paths.keys().forEach( (key)=>routers.push(paths(key).default) ) } getALLRouterMsg(require.context('.',true,/\.router\.js/)) exportdefaultnewRouter({ routes:[ { path:'/', name:'Home', component:Home, children:[ ...routers ] } ] })
以上就是本次介绍的全部知识点内容,感谢大家对毛票票的支持。