Vue3動態添加路由及解決頁面刷新空白問題


1、route/index.ts 寫入靜態路由及動態路由

 
         
// 靜態路由
export const constantRouterMap = [
  {
    path: '/',
    redirect: '/home/index',
  },
  {
    path: '/home',
    component: component,
    meta: { title: '首頁',},
    redirect: '/home/index',
    children: [
      {
        path: 'index',
        name: 'HomeIndex',
        component: () => import('../views/home/index.vue'),
        meta: { title: '首頁',  keepAlive: true }
      },
    ]
  },
]

// 動態路由
export const asyncRouterMap = [
  {
    path: '/xxx',
    component: component,
    meta: { title: 'xxx' },
    redirect: '/xxx',
    children: []
  },
  ...
]

const router = createRouter({
 history: createWebHashHistory()
 routes: constantRouterMap // 只寫靜態路由
})
 

2、store/index.ts寫入接口請求回來的權限路由

 1 const res = await get_menu_list(params)   
 2 //根據唯一值過濾動態路由權限數據
 3 const addMenuList = res.map(i => i?.code).filter(Boolean)
 4 asyncRouterMap.forEach(item => {
 5    if(item.children) {
 6       item.children = item.children.filter(cItem => addMenuList.indexOf(cItem.meta?.code) !== -1)  
 7    }
 8    // Router4中,去掉了 router.addRoutes ,只能使用 addRoute單個添加
 9    router.addRoute(item)
10 })  
11                   

寫到這里,動態路由添加就成功了,在點擊菜單跳轉之后一切正常,但是瀏覽器刷新一下,頁面就變成了空白。

此刻,需要在路由跳轉前判斷是否被添加成功

// 設置flag,防止非權限路由,頁面死循環重定向
let flag = 0
router.beforeEach((to, from, next) => {
  if (flag === 0 && to.matched.length == 0) { 
    flag++
    router.push(to.path); 
  } else if (flag !== 0 && to.matched.length == 0) { 
    next('/')
  } else {
    next()
  }
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM