1 修改 router.ts 文件

import { addActiveRoutes } from './activeRoutes'

let init = true
router.beforeEach((to, from, next) => {
// 刷新时重新加载动态路由
if (init) {
init = false
addActiveRoutes()
next(to)
return
}
})

export default router

2 添加 activeRoutes.ts 文件

import type { RouteRecordRaw } from 'vue-router'

const errorRoute = {
path: '/:pathMatch(.*)',
name: 'Error',
component: () => import('@/views/Error.vue'),
}

const activeRoutes: RouteRecordRaw[] = [
{
path: '/A',
name: 'A',
component: () => import('@/A.vue')
},
{
path: '/B',
name: 'B',
component: () => import('@/B.vue')
}
]

export const addActiveRoutes = () => {
if (***) { // 添加判断条件
activeRoutes.forEach((route) => {
if (router.hasRoute(route.name)) return // 避免重复添加
router.addRoute(route)
// router.addRoute('Parent', route) // 若是某个路由的子路由,第一个参数为该路由name
})
}
// 错误路由必须在动态路由后添加,否则会被匹配上
router.addRoute(errorRoute)
}

export const removeActiveRoutes = () => {
activeRoutes.forEach((route) => {
if (router.hasRoute(route.name)) {
router.removeRoute(route.name)
}
})
router.removeRoute('Error')
}

3 修改登录 Vue 文件

import { addActiveRoutes } from '@/router/activeRoutes'
// 登录成功后调用
addActiveRoutes()

4 修改退出登录 Vue 文件

import { removeActiveRoutes } from '@/router/activeRoutes'
// 退出登录成功后调用
removeActiveRoutes()