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中怎么实现路由动态加载的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注编程网行业资讯频道,感谢各位的阅读!