element-admin通過後端動態路由表實現使用者許可權控制(一)

han1140521792發表於2020-07-10

實現效果描述

    最近大家都說牛市來了,我也在瘋狂的理財,主要買了一些基金,然後做了系統,可以實時檢視基金漲跌情況,同事覺得好用,叫我給他開賬戶,於是我就開始研究起了許可權來了,最後實現效果如下:

A使用者左側導航條:

B使用者左側導航條

實現方案

後端返回路由結構如下:

"user_router": [
    {
      "component": "/dashboard/index", 
      "icon": "form", 
      "id": 14, 
      "name": "dashboard", 
      "path": "dashboard", 
      "title": "\u9996\u9875", 
      "uid": 5
    }, 
    {
      "component": "/alipay/fund", 
      "icon": "form", 
      "id": 15, 
      "name": "alipay", 
      "path": "alipay", 
      "title": "\u652f\u4ed8\u5b9d", 
      "uid": 5
    }
  ]

修改專案中的permission.js

新增如下程式碼:

// get user info
  const res = await store.dispatch('user/getInfo')
  store.dispatch('user/generateRouter', res.user_router).then(() => {
  const routers = store.getters.addRouters
  router.addRoutes(store.getters.addRouters)
  routers.forEach((item, index) => {
  router.options.routes[index] = item
   })
   next({
   ...to,
   replace: true
    })
   })

插入位置為:

修改 store/modules/user.js,在action中新增generateRouter函式,如下程式碼

generateRouter({
    commit
  }, routers) {
    return new Promise((resolve) => {
      const accessedRouters = formatRouter(routers)
      commit('SET_ROUTERS', accessedRouters);
      resolve();
    })
  },

其中fomatRouter函式程式碼為:

const formatRouter = (routers) => {
  const formatRouters = [];
  routers.forEach(router => {
    const path = router.path;
    const name = router.name;
    const title = router.title;
    const component = router.component;
    const icon = router.icon;
    const formatRouter = {
      path: '/',
      component: Layout,
      redirect: '/' + name,
      children: [{
        path: path,
        name: name,
        component(resolve) {
          require(["@/views" + component], resolve)
        },
        meta: {
          title: title,
          icon: icon
        }
      }]
    }

    formatRouters.push(formatRouter)
  })

 另外在getDefaultState函式中新增如下兩個變數

routers: constantRoutes,
addRouters: []

位置如下:

在getters.js中新增如下:

addRouters: state => state.user.addRouters

以上程式碼均在vue-element-admin程式碼庫基礎上修改的 

總結

  • 參考思路https://juejin.im/post/591aa14f570c35006961acac
  • 難點,之前以為直接將路由物件拼接到addRoutes函式中即可,實際上是需要對從後端取過來的資料進行format,否則不生效
  • 個人是前端後端一起做,後端用的python flask框架,就考慮了後端用資料庫儲存路由表

有問題歡迎各位諮詢,這是我的公眾號,大家可以關注一下:

 

相關文章