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:'https://www.jb51.net/', 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:'https://www.jb51.net/', 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:'https://www.jb51.net/', name:'Home', component:Home, children:[ ...routers ] } ] })

以上就是本次介绍的全部知识点内容,感谢大家对脚本之家的支持。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/0cecdb3a54f8a13c13ac606c78e46b0e.html