vue3動(dòng)態(tài)路由addRoute實(shí)例詳解
Vue2中,有兩種方法實(shí)現(xiàn)路由權(quán)限動(dòng)態(tài)渲染:
router.addRoute(parentOrRoute, route) //添加單個(gè) router.addRoutes(routes) //添加多個(gè)
但在Vue3中,只保留了 addRoute() 方法。
首先,假設(shè)路由如下:
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()
}
})使用這種拼接的方式會(huì)導(dǎo)致全局scss多次注入錯(cuò)誤,而且需要后臺(tái)返回文件路徑。

所以改用以下方式:
// 在本地建一個(gè)路由表
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 //沒(méi)找到則用默認(rèn)框架組件
})
// 是否存在子集
if (itemRouter.children && itemRouter.children.length) {
list[index].children = dynamicRouter(itemRouter.children);
}
})
return list
}如果出現(xiàn) Error: Invalid route component ,看下路徑是否正確,還有 addRoute 里傳的是否是對(duì)象,一開(kāi)始傳了數(shù)組導(dǎo)致找了半天(扶額

以上。
到此這篇關(guān)于vue3動(dòng)態(tài)路由addRoute的文章就介紹到這了,更多相關(guān)vue3動(dòng)態(tài)路由addRoute內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue使用video.js實(shí)現(xiàn)播放m3u8格式的視頻
這篇文章主要為大家詳細(xì)介紹了vue如何使用video.js實(shí)現(xiàn)播放m3u8格式的視頻,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12
vue el-upload手動(dòng)上傳實(shí)現(xiàn)過(guò)程
這篇文章主要介紹了vue el-upload手動(dòng)上傳實(shí)現(xiàn)過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
vue學(xué)習(xí)筆記之指令v-text && v-html && v-bind詳解
這篇文章主要介紹了vue學(xué)習(xí)筆記之指令v-text && v-html && v-bind詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05
vue+element-ui表格自定義列模版的實(shí)現(xiàn)
本文主要介紹了vue+element-ui表格自定義列模版的實(shí)現(xiàn),通過(guò)插槽完美解決了element-ui表格自定義列模版的問(wèn)題,具有一定的參考價(jià)值,感興趣的可以了解一下2024-05-05

