动态路由加载

重置初始路由逻辑:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const routes = [
{ path, name, component },
...
]

const createRouter = () => new VueRouter({ routes })

const router = createRouter()

function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher
}

export { router, resetRouter }

动态加载逻辑:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
resetRouter() // 重置路由

const addRoutes = [..., { path, name, component }]

// 404页面必须最后加
addRoutes.push({
path: '*',
name: '__any__',
redirect: to => {
return {
name: 'ErrorPage',
}
},
})
for (const route of addRoutes) {
router.addRoute(route)
}

一般是需要在router.beforeEach进行动态路由添加,且next必须使用以下方法进行

1
2
3
4
router.beforeEach(async (to, from, next) => {
// ...动态添加路由操作
next({ ...to, replace: true }) // hack方法 确保addRoute已完成
})