Vue路由模块化配置的完整步骤

2020-06-12 21:26:46易采站长站整理

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