Vue | 自定義指令和動態路由實現權限控制


功能概述:

  • 根據后端返回接口,實現路由動態顯示
  • 實現按鈕(HTML元素)級別權限控制

涉及知識點:

  • 路由守衛
  • Vuex使用
  • Vue自定義指令

導航守衛

前端工程采用Github開源項目Vue-element-admin作為模板,該項目地址:Github | Vue-element-admin

Vue-element-admin模板項目的src/permission.js文件中,給出了路由守衛、加載動態路由的實現方案,在實現了基於不同角色加載動態路由的功能。我們只需要稍作改動,就能將基於角色加載路由改造為基於權限加載路由。

導航守衛:可以應用於在路由跳轉時,對用戶的登錄狀態或權限進行判斷。項目中使用全局前置守衛。參考Vue官方文檔:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html

后台返回接口

getUserInfo接口返回用戶信息和路由、操作權限等
權限系統后台采用基於角色的權限控制方案(role-based access control),如上圖所示,
該用戶信息接口將查詢用戶所具有的所有角色,再將這些角色的權限並集按照路由 - 操作整合在一起返回。在用戶登錄入系統后,我們從后台請求獲得用戶信息(個人信息 + 權限信息),作為全局屬性儲存在前端。不同權限的用戶看到的頁面不同,依賴於這些屬性,它們決定了路由如何加載、頁面如何渲染。

這種多個組件依賴一組屬性的場景,Vue提供了VueX作為全局狀態管理方案。

使用VueX存儲權限信息

src/store/moudules目錄下定義permission.js

1.定義異步方法,方法內部包含HTTP請求從后台拉取數據

import http from '../../axios';
async function getUserInfo() {
  const res = await http.getUserInfo();
  return res;
}

使用await關鍵字,保證執行順序正確。這里是為了保證能拿到接口返回的內容,以便於下一步處理。

const actions = {
  getPermissions({ commit }) {
    return new Promise(resolve => {
      getUserInfo().then(res => {
        if (res) {
          let permissionList = res.permissionList;
          commit('SET_PERMISSIONS', permissionList);
          // 根據后台返回的路由,生成實際可以訪問的路由
          let accessRoutes = filterAsyncRoutesByPermissions(asyncRoutes, permissionList);
          commit('SET_ROUTES', accessRoutes);
          commit('SET_USER_INFO', { name: res.name, accountName: res.accountName })
          resolve(accessRoutes);
        } else {
          resolve([]);
        }
      }).catch(() => resolve([]));
    })
  }
}

VueX中action定義異步方法。

2. 定義靜態、動態路由

src/router/index.js
靜態路由:

export const constantRoutes = [
    {
        path: '/redirect',
        component: Layout,
        hidden: true,
        children: [
            {
                path: '/redirect/:path(.*)',
                component: () => import('@/views/redirect/index'),
            },
        ],
    ,
  ...
    {
        path: '/404',
        component: () => import('@/views/error-page/404'),
        hidden: true,
    }
];

動態路由:

export const asyncRoutes = [
    {
        path: '/system',
        component: Layout,
        name: '系統管理',
        meta: { title: '系統管理', icon: 'el-icon-user', affix: true },
        children: [
            {
                path: '/system',
                component: () => import('@/views/management/system/Index'),
                meta: { title: '系統管理', icon: 'el-icon-setting', affix: true },
            },
        ],
    }
...
]

靜態路由中定義了所有用戶均可訪問的路由,動態路由中定義了動態加載的路由。

3.根據權限過濾並排序路由

export function filterAsyncRoutesByPermissions(routes, menus) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    let index = menus.map(menu => menu.url).indexOf(tmp.path);
    if (index != -1) {
      // 后端返回路由信息覆蓋前端定義路由信息
      tmp.name = menus[index].name;
      // debugger;
      tmp.meta.title = menus[index].name;
      tmp.children.forEach(child => {
        if (child.path == tmp.path) {
          child.meta.title = tmp.meta.title;
        }
      })
      res.push(tmp)
    }
  });
  // 根據返回菜單順序,確定路由順序
  /**
   * TODO 子菜單排序
   */
  res.sort((routeA, routeB) => menus.map(menu => menu.url).indexOf(routeA.path) - menus.map(menu => menu.url).indexOf(routeB.path))
  return res
}

根據url匹配,匹配到url的路由則加入數組。最終用戶可以訪問的路由 = 允許訪問的動態路由 + 不需要權限的靜態路由。

4.src/permission.js中的處理邏輯

// 引入store
import store from './store';
const whiteList = ['/login', '/auth-redirect']; // no redirect whitelist

// 路由守衛
router.beforeEach(async (to, from, next) => {
    //start progress bar
    NProgress.start()
    if (hasToken) {
        if (to.path === '/login') {
          // ... 省略登出邏輯
            NProgress.done();
        } else {    
            // 查看是否已緩存過動態路由
            const hasRoutes = store.getters.permission_routes && store.getters.permission_routes.length > 0;
            if (hasRoutes) {
                next();
            } else {
                try {
                    const accessRoutes = await store.dispatch('permission/getPermissions');
                    router.addRoutes(accessRoutes);
                    const toRoute = accessRoutes.filter((route) => route.path == to.path);
                    next({ path: toRoute.length > 0 ? toRoute[0].path : accessRoutes[0].path, replace: true });
                } catch (error) {
                    next(`/login?redirect=${to.path}`);
                    NProgress.done();
                }
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            // in the free login whitelist, go directly
            next();
        } else {
            next(`/login?redirect=${to.path}`);
            NProgress.done();
        }
    }
});

router.afterEach(() => {
    // finish progress bar
    NProgress.done();
});

以上是動態路由實現方案。


Vue支持自定義指令,用法類似於Vue原生指令如v-modelv-on等,網上查閱到的大部分細粒度權限控制方案都使用這種方法。下面將給出我的實現。

自定義指令

自定義指令 v-permission

src/directive/permission/index.js

import store from '@/store'
 export default {
  inserted(el, binding, vnode) {
    const { value } = binding
    const permissions = store.getters && store.getters.permissions;
    if (value) {
      // 獲取當前所掛載的vue所在的上下文節點url
      let url = vnode.context.$route.path;
      let permissionActions = permissions[url];
      // console.log(permissionActions)
      const hasPermission = permissionActions.some(action => {
        if (value.constructor === Array) {
          // 或判斷: 只要存在任1,判定為有權限
          return value.includes(action);
        } else {
          return action === value;
        }
      })
      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error(`need further permissions!`)
    }
  }
}

后端給出的權限數據是路由(url)與操作的對應Map,url可以通過將要掛載到的vnode屬性拿到。這個方法有點類似於AOP,在虛擬元素掛載之后做判斷,如果沒有權限則從父元素上移除掉。
使用方法:

  • 舉例一:單個按鈕 (注意雙引號套單引號的寫法)
  <el-button @click.native.prevent="editUser(scope.row)" type="text" size="small" v-permission="'op_edit'">
                                編輯
 </el-button>
  • 舉例二:或判斷(傳入數組),只要擁有數組中一個權限,則保留元素,所有權限都沒有,則移除。
    在上一篇博客https://www.jianshu.com/p/066c4ce4c767
    下拉菜單上增加控制:
    dot-dropdown
    數據定義
    相應數據定義中增加action屬性。

該方法無法覆蓋所有場景,所以依然給出相應工具類:

/**
 * 
 * @param {*當前頁面路由} url 
 * @param {*操作code e.g op_add } value 
 * @return true/false 是否有該項權限
 */
function checkPermission(url, value) {

    const permissions = store.getters && store.getters.permissions;
    let permissionActions = permissions[url];

    if (!permissionActions) {
        return false;
    }

    let hasPermission = permissionActions.some(action => {
        if (value.constructor === Array) {
            // 或判斷: 只要存在任1,判定為有權限
            return value.includes(action);
        } else {
            return action === value;
        }
    });
    return hasPermission;

}

以上完成按鈕粒度權限控制。


免責聲明!

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



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