快活林资源网 Design By www.csstdc.com

首先新建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
   ]

  }
 ]
})

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

快活林资源网 Design By www.csstdc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
快活林资源网 Design By www.csstdc.com