前端vue-element-template(二)動(dòng)態(tài)路由

這個(gè)章節(jié)知識(shí)點(diǎn)不多,但是很繞,而且我覺(jué)得不是最優(yōu)雅的寫(xiě)法,如果有更好的方法請(qǐng)給我留言

參考文章

https://www.cnblogs.com/langhaoabcd/p/11346227.html

簡(jiǎn)單分析

  • 主要利用 router.addRoutes([]) //傳入數(shù)組

  • global.antRouter = menus //賦值全局變量

  • Siderbar/index return this.$router.options.routes.concat(global.antRouter) //路由合并

  • 到此就完成了

通過(guò)permission.js開(kāi)始獲取權(quán)限管理

  • await store.dispatch('user/getInfo')
  • store/modules/user.js //這里通過(guò)vuex發(fā)起請(qǐng)求
  • 此時(shí)getinfo包含改用戶的權(quán)限信息
  • 后端返回?cái)?shù)據(jù)即可,前端處理成符合菜單的格式
  • 存入到store中
function toTreeData(data,pid){
  function tree(id) {
    let arr = []
    data.filter(item => {
      return item.id_parentauth === id;
    }).forEach(item => {
      // console.log(item.href)
      let jsonpath = {
        path: item.href,
        name: item.name,
        meta:{title:item.name, icon: item.icon},
        children: tree(item.id_auth)
      }
      if(!Boolean(item.id_parentauth)){
        jsonpath.component = Layout
        // jsonpath.redirect = '/example/table'
      }else {
        //解決import無(wú)法導(dǎo)入的問(wèn)題
        jsonpath.component =  (resolve) => require([`@/views/${item.href}/index`], resolve)
      }
      arr.push(jsonpath)
    })
    return arr
  }
  return tree(pid) // 第一級(jí)節(jié)點(diǎn)的父id,是null或者0,視情況傳入
}

最后一步獲取vuex的menu并放入addRouters

  • const menus = store.getters.menus
  • router.addRoutes(menus) // 2.動(dòng)態(tài)添加路由
  • global.antRouter = menus // 3.將路由數(shù)據(jù)傳遞給全局變量,做側(cè)邊欄菜單渲染工作
  • 合并路由 this.$router.options.routes.concat(global.antRouter) //路由合并
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容