Vue2-利用自定義指令實現按鈕許可權控制

相遇就是有缘發表於2024-07-13

檔案結構

新建directive目錄,並在該目錄下新增permission目錄,在permission目錄下新增hasPerm.js和index.js。

檔案內容

hasPerm.js

//操作按鈕許可權控制
import store from "@/store";

export default {
  /**
   * 被繫結元素插入父節點時呼叫
   * @param {*} el 指令繫結的元素
   * @param {*} binding 指令資訊
   * @param {*} vnode 虛擬DOM節點
   */
  inserted(el, binding, vnode) {
    const { value } = binding;
    const all_permission = "*:*:*";
    const permissions = store.getters && store.getters.permissions;

    if (value && value instanceof Array && value.length > 0) {
      const permissionFlag = value;

      const hasPermissions = permissions.some((permission) => {
        return (
          all_permission === permission || permissionFlag.includes(permission)
        );
      });

      if (!hasPermissions) {
        el.parentNode && el.parentNode.removeChild(el);
      }
    } else {
      throw new Error(`請設定操作許可權標籤值`);
    }
  },
};

index.js

import hasPerm from './hasPerm'

const install = function(Vue) {
  Vue.directive('hasPerm', hasPerm)
}

if (window.Vue) {
  window['hasPerm'] = hasPerm
  Vue.use(install);
}

export default install

全域性註冊

main.js

import permission from './directive/permission'
Vue.use(permission)

Vuex部分

store→getter.js

const getters = {
     permissions:state=>state.user.permissions
}
export default getters

store→modules→user.js

import { getInfo } from "@/api/user";
import { getToken } from "@/utils/auth";

const getDefaultState = () => {
  return {
    token: getToken(),
    permissions: [],
  };
};

const user = {
  state: getDefaultState(),
  mutations: {
    SET_PERMISSION: (state, permissions) => {
      state.permissions = permissions;
    },
  },

  actions: {
    //獲取當前登入使用者資訊
    getInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token)
          .then((res) => {
            const { data } = res;
            if (!data) {
              return reject("Verification failed, please Login again.");
            }
            const { permissions } = data;
            commit("SET_PERMISSION", permissions);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    }
};

export default user;

呼叫

<el-button size="mini" v-hasPerm="['system:role:delete']" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">刪除</el-button>

相關文章