vue3動態(tài)路由addRoute實例詳解
Vue2中,有兩種方法實現(xiàn)路由權限動態(tài)渲染:
router.addRoute(parentOrRoute, route) //添加單個 router.addRoutes(routes) //添加多個
但在Vue3中,只保留了 addRoute() 方法。
首先,假設路由如下:
const menu = [{
id: 'system-manage',
name: 'system-manage',
path: '/system',
meta:{
title: '系統(tǒng)管理',
icon: 'setting',
},
compoent: 'layout',
children: [
{
id: 'role',
name: 'role',
path: '/system/role',
meta:{
title: '角色管理',
icon: 'user-filled',
},
compoent: 'view/system/role',
children: []
}
]
}]// 遞歸替換引入component
function dynamicRouter(routers) {
const list = []
routers.forEach((itemRouter,index) => {
list.push({
...itemRouter,
component: ()=>import(`@/${itemRouter.component}`)
})
// 是否存在子集
if (itemRouter.children && itemRouter.children.length) {
list[index].children = dynamicRouter(itemRouter.children);
}
})
return list
}
// 防止首次或者刷新界面路由失效
let registerRouteFresh = true
router.beforeEach((to, from, next) => {
if (registerRouteFresh) {
// addRoute允許帶children添加,所以循環(huán)第一層即可
dynamicRouter(menu).forEach((itemRouter) => {
router.addRoute(itemRouter)
})
next({ ...to, replace: true })
registerRouteFresh = false
} else {
next()
}
})使用這種拼接的方式會導致全局scss多次注入錯誤,而且需要后臺返回文件路徑。

所以改用以下方式:
// 在本地建一個路由表
const path = [{
path: '/system/role',
name: '角色管理',
component: () => import('@/views/system/role')
}]
function dynamicRouter(routers) {
const list = []
routers.forEach((itemRouter,index) => {
// 從本地找組件
const authRoute = path.find(i=>i.path==itemRouter.path)
list.push({
...itemRouter,
component: authRoute?.component || Layout //沒找到則用默認框架組件
})
// 是否存在子集
if (itemRouter.children && itemRouter.children.length) {
list[index].children = dynamicRouter(itemRouter.children);
}
})
return list
}如果出現(xiàn) Error: Invalid route component ,看下路徑是否正確,還有 addRoute 里傳的是否是對象,一開始傳了數(shù)組導致找了半天(扶額

以上。
到此這篇關于vue3動態(tài)路由addRoute的文章就介紹到這了,更多相關vue3動態(tài)路由addRoute內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue使用video.js實現(xiàn)播放m3u8格式的視頻
這篇文章主要為大家詳細介紹了vue如何使用video.js實現(xiàn)播放m3u8格式的視頻,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2023-12-12
vue學習筆記之指令v-text && v-html && v-bind詳解
這篇文章主要介紹了vue學習筆記之指令v-text && v-html && v-bind詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
vue+element-ui表格自定義列模版的實現(xiàn)
本文主要介紹了vue+element-ui表格自定義列模版的實現(xiàn),通過插槽完美解決了element-ui表格自定義列模版的問題,具有一定的參考價值,感興趣的可以了解一下2024-05-05

