vue3 addRoute 动态添加路由
vue3 动态添加路由删除动态路由结合 vuexmenuList
·
vue3 动态添加路由 删除动态路由
动态添加路由
/**
* 前置导航守卫
* 动态添加路由 刷新消失
* A 前端 全部配置好 meta: { roles: ['0'] } 通过 roles匹配
* 修改时 前端也要同步修改
*
* B 数据全部由 后台提供 完全动态渲染
* 1 登录页 中 获取 MenuList 中包含 router 存入 vuex
* 2 beforeEach 中 添加动态路由
* 指定 部分页面 不参与 动态添加 目前 '/login'
* 静态路由的数量 === 路由栈的数量 说明首次 添加
* next({ path: "/home", replace: true })--二级路由 首页为 /home
* 必须指定 path: "/home" 初始化时 二级路由首页才会展示 相当于 跳转两次
*
* next({}) 修改 相当于 重定向 所以会再次进入 beforeEach
* 如果还是 next({}) 相当于 再次 路由跳转 直到遇到 next() 停止
* 无论怎么 跳转 最后一定要 原生 的 next() 停止
*/
const filterRoutes = ['/login']
router.beforeEach(async (to, from, next) => {
console.log(to)
console.log(router.getRoutes().length)
// console.log(router.options.routes, router.getRoutes())
// 在 主页路由中 才 动态添加
if (!filterRoutes.includes(to.path)) {
// 静态路由的数量 === 路由栈的数量 children存在 说明首次 添加
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()
}
})
// vuex dispatch menuList
const asyncMenuList = async () => {
const data = await store.dispatch('common/getMenuList')
return dynamicAddRoutes(data)
}
// 动态 添加 routes
const dynamicAddRoutes = MenuList => {
// const MenuList = store.state.common.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}`),
})
})
})
}
})
// vuex更改动态路由
store.commit('common/setRouteList', routes)
return routes
删除动态路由
// 重置
export const resetRouter = () => {
const routes = store.state.common.routeList
routes && routes.forEach(route => router.removeRoute(route.name))
}
更多推荐



所有评论(0)