# 异步加载路由

路由表为后端返回的,需要从接口获取,并过滤。

首先静态路由还是照常写

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)



const syncRoutes = [
  {
    path: '/',
    name: 'Home',
    component: () => import(/* webpackChunkName: "about" */ '../views/Home.vue')
  },
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.routerBase,
  routes: syncRoutes
})

export default router
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

接着获取路由表,遍历处理数据得到asyncRoutes

import router from './index'
import { getRoutes } from '../api/home'

type VueRoute = {
  path: string
  name: string
  component: () => object
}

let asyncRoutes: Array<VueRoute> = []
let webRoutes: Array<VueRoute> = []
async function initRoutes() {
  let res = await getRoutes()
  if (res.status === 200) {
    console.log(res.data.data)
    webRoutes = res.data.data
    return res.data.data
  }
}

// // eslint-disable-next-line
async function handleAsyncRoutes() {
  let asyncRouteMap = await initRoutes()
  console.log('asyncRoutes: ', asyncRouteMap)
  asyncRoutes = asyncRouteMap.map((route: VueRoute) => ({
    path: route.path,
    name: route.name,
    component: () => import(`@/views/${route.component}`)
  }))
  asyncRoutes.forEach((routeConfig) => {
    if (routeConfig.name !== 'Home') {
      router.addRoute(routeConfig)
    }
  })
}

handleAsyncRoutes()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

最后别忘了在main.js里调用