亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

vue3動(dòng)態(tài)路由addRoute實(shí)例詳解

 更新時(shí)間:2023年09月07日 11:07:55   作者:fml海棠  
這篇文章主要介紹了vue3動(dòng)態(tài)路由addRoute的相關(guān)知識(shí),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

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)返回文件路徑。

scss報(bào)錯(cuò)

所以改用以下方式:

// 在本地建一個(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 //沒找到則用默認(rèn)框架組件
    })
    // 是否存在子集
    if (itemRouter.children && itemRouter.children.length) {
      list[index].children = dynamicRouter(itemRouter.children);
    }
  })
  return list
}

如果出現(xiàn) Error: Invalid route component ,看下路徑是否正確,還有 addRoute 里傳的是否是對(duì)象,一開始傳了數(shù)組導(dǎo)致找了半天(扶額

Invalid route

以上。

到此這篇關(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)文章

最新評(píng)論