Vue 路由模組化配置

  • 2019 年 10 月 3 日
  • 筆記

部落格地址:https://ainyi.com/77

企業運營後台頁面很多,路由如若不區分模組化配置,所有路由擠在同一個文件將不好維護,所以路由的配置也要模組化

分享兩個解決方案 —— Vue 路由配置的模組化(==Plan A== and ==Plan B==)

註冊需要

首先路由註冊需要啥

// main.js    new Vue({    el: '#app',    router,    store,    components: { App },    template: '<App/>'  })    // 這裡的 router 是這樣的  export default new Router({    mode: 'history',    routes: [],    ... // 其他配置  })

也就是說註冊需要 new 一個 Router 實例,實例里的 routes 是數組,裡面配置每個頁面的路由

模組拆分(Plan A)

src 下 router 的目錄結構

---src  ----router  ------modules  --------xxxx.js // 模組 xxx  --------other.js // 模組 other  ------index.js // 路由配置入口和出口 index

例如

然後配置 modules 裡面模組路由

// 配置 other  import err from '@/views/others/Error.vue'  export default function(router) {    router.push({      path: '/error',      name: 'error',      component: err    })  }
// 配置 accoutReport  export default function(router) {    router.push({      path: '/accout-report',      redirect: '/accout-report/list'    })    // 列表    router.push({      path: '/accout-report/list',      name: 'list',      component: () => import('@/views/accoutReport/List.vue')    })    // 新增    router.push({      path: '/accout-report/create',      name: 'create',      component: () => import('@/views/accoutReport/Create.vue')    })    // 編輯    router.push({      path: '/accout-report/edit/:id',      name: 'edit',      component: () => import('@/views/accoutReport/steps/CreateStep2.vue')    })    // 詳情    router.push({      path: '/accout-report/detail/:id',      name: 'detail',      component: () => import('@/views/accoutReport/Detail.vue')    })  }

如有其他模組,依次像上面一樣配置

關鍵是路由配置入口出口文件 index.js

// index.js  import Vue from 'vue'  import Router from 'vue-router'  import App from '@/views/Layouts.vue'  import otherRouter from '@/router/modules/others'  import accoutReport from '@/router/modules/accoutReport'  // import store from '@/stores'  Vue.use(Router)    let routes = []    let rootRouter = {    path: '/',    component: App,    children: [],    redirect: '/accout-report/list'  }    let redirectRouter = {    path: '*',    redirect: '/error'  }    otherRouter(rootRouter.children)  accoutReport(rootRouter.children)  // 如有多個模組,依次在這裡配置    const router = new Router({    mode: 'history',    routes: routes.concat([rootRouter, redirectRouter])  })  export default router  

上述程式碼,除了 other,所有頁面路由配置在 rootRouter 的 children 下面,有一個父級 router 包裹著

程式碼都看得懂,這裡就不多說哈~

最後在 main.js 中註冊

模組拆分(Plan B)

該方法較為難懂一些,可以看看

目錄結構跟 Plan A 類似,不過在 src 下多了一個 router.js 配置文件作為路由出口文件

src 下 router 的目錄結構

---src  ----router  ------modules  --------xxxx.js // 模組 xxx  --------other.js // 模組 other  ------index.js // 路由配置中轉文件  ----router.js // 路由配置出口文件

例如

模組 modules 里文件配置

// order.js  import { getFindBusinessServiceList } from '@/utils/config-utils'    const OrderRouter = [    {      path: '/',      redirect: '/cost/order-list'    },    {      path: '/cost',      component: () => import('@/views/Layouts'),      redirect: '/cost/order-list',      children: [        {          path: 'order-list',          component: () => import('@/views/orderManagement/List'),          beforeEnter: async (to, from, next) => {            await getFindBusinessServiceList() // 進入該路由前非同步請求,結束後進入該路由            next()          }        },        {          path: 'order-detail',          component: () => import('@/views/orderManagement/Detail')        },        // 下面是重定向,可不配置        {          path: 'orderDetail',          redirect: 'order-detail'        },        {          path: 'order',          redirect: 'order-list'        }      ]    }  ]  export default OrderRouter

上述路由配置在 Layouts 路由下的 children

接下來關鍵,路由配置中轉文件 index.js
遍歷 modules 文件夾下的每個模組文件,賦值和導出

// index.js  import { camelCase } from 'lodash-es'  const requiredModules = require.context('./modules', false, /.js$/)  const routers = {}    requiredModules.keys().forEach(fileName => {    // 不載入index.js    if (fileName === './index.js') return    // 轉為駝峰命名    const moduleName = camelCase(fileName.replace(/(./|.js)/g, ''))      routers[moduleName] =      requiredModules(fileName).default || requiredModules(fileName)  })  export default routers

然後在 src 下的出口文件 router.js 包裝

// router.js  import Vue from 'vue'  import Router from 'vue-router'  import routers from '@/routers/index'  Vue.use(Router)  let routes = []  Object.values(routers).forEach(router => {    routes.push(...router)  })    export default new Router({    mode: 'history',    routes  })

最後在 main.js 中註冊

部落格地址:https://ainyi.com/77