vue3 动态添加路由 删除动态路由
动态添加路由
const filterRoutes = ['/login']
router.beforeEach(async (to, from, next) => {
console.log(to)
console.log(router.getRoutes().length)
if (!filterRoutes.includes(to.path)) {
if (router.getRoutes().length <= 3) {
const list = await asyncMenuList()
list.forEach(route => router.addRoute('mainHome', route))
next({ path: to.path, replace: true })
}
next()
} else {
next()
}
})
const asyncMenuList = async () => {
const data = await store.dispatch('common/getMenuList')
return dynamicAddRoutes(data)
}
const dynamicAddRoutes = MenuList => {
const routes = []
MenuList.forEach(item => {
if (!item.children) {
routes.push({
path: item.path,
name: item.name,
component: () => import(`@/views${item.url}`),
})
} else {
item.children.forEach(item => {
item.obj.forEach(item => {
routes.push({
path: item.path,
name: item.name,
component: () => import(`@/views${item.url}`),
})
})
})
}
})
store.commit('common/setRouteList', routes)
return routes
删除动态路由
export const resetRouter = () => {
const routes = store.state.common.routeList
routes && routes.forEach(route => router.removeRoute(route.name))
}