后台管理权限自定义按钮指令v-hasPermi

第一步:在src下面建立一个自定义指令文件,放自定义指令方法

permission.js文件:

/**
 * v-hasPermi 操作权限处理
 */

import store from "@/store";

export default {
  inserted(el, binding) {
    const { value } = binding;
    //从仓库里面获取到后台给的数组
    const permission = store.getters && store.getters.permissions;
    console.log("permission===", permission);
    if (value && Array.isArray(value) && value.length > 0) {
      const hasPermissions = permission.some((item) => {
        return value.includes(item.perms);
      });

      if (!hasPermissions) {
        el.parentNode && el.parentNode.removeChild(el);
      }
    } else {
      throw new Error(`未设置权限`);
    }
  },
};

index.js文件:

import hasPermi from './permission'

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

export default install

后端返回的数据结构:

第二步:在main.js里面引入注册自定义指令

// 自定义指令
import directives from "./directives/index";
Vue.use(directives);

第三步:vuex仓库里面存放后端接口返回的用于控制权限按钮的数组

vuex里面需要用到的三个文件,可根据自身需求进行添加:

user.js

import { userInfo } from "@/api/system/login";
//封装的统一存本地的方法,可自行添加
import { mySessionStorage } from "../../../utils/encryption";

const user = {
  state: {
    permissions: mySessionStorage.getItem("permissionArray") || [],
  },
  actions: {
    // 获取用户信息
    getUserInfo({ commit }) {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await userInfo();
          if (res.code === 200) {
            commit("SET_PERMISSION", res.data.authorities);
            resolve(res);
          } else {
            reject(res);
          }
        } catch (error) {
          reject(error);
        }
      });
    },
  },
  mutations: {
    SET_PERMISSION: (state, permission) => {
      state.permission = permission || [];
      //把获取到的路由存本地
      mySessionStorage.setItem("permissionArray", state.permission);
    },
  },
};
export default user;

index.js

import Vue from "vue";
import Vuex from "vuex";
import user from "./modules/user";
import getters from "./getters";


Vue.use(Vuex);
const store = new Vuex.Store({
  modules: {
    user,
  },
  getters,
});

export default store;

getters.js

const getters = {
  permissions: (state) => state.Layout_store.permissions,
};
export default getters;

user.js里面的getUserInfo函数放在合适的地方调用,这里是放在登录页面:

关于页面使用:

关于页面操作按钮过多,固定展示两个,其他放入更多里面:

首先utils里面定义一个函数计算权限:

import store from "@/store";

// 校验权限

export const hasPermi = (arr) => {

return store.getters.permission.some((role) => {

return arr.includes(role);

});

};

页面使用:

import { hasPermi } from '@/util/util'

// 获取table数据

async getTableLists() {

this.loading = true

const params = {

...this.queryForm,

...this.form,

startTime: this.startTime,

endTime: this.endTime,

}

delete params.time

const res = await certificateList(params)

if (res.code === 200) {

this.tableData = res.data.records

this.tableData = res.data.records.map((item) => {

item.permissionList = []

if (hasPermi(['certificate_view'])) {

item.permissionList.push({ viewBtn: true })

}

if (hasPermi(['certificate_edit']) && item.issueSize == 0) {

item.permissionList.push({ editBtn: true })

}

if (hasPermi(['certificate_delete'])) {

item.permissionList.push({ deleteBtn: true })

}

if (hasPermi(['certificate_record'])) {

item.permissionList.push({ recordBtn: true })

}

return item

})

this.total = parseInt(res.data.total)

this.loading = false

} else {

this.$message.error(res.msg)

this.loading = false

}

},

html代码:

   <el-table-column align="center" label="操作" fixed="right" width="200">
          <template slot-scope="scope">
            <div
              v-for="(item, index) in scope.row.permissionList.length > 3
                ? scope.row.permissionList.slice(0, 2)
                : scope.row.permissionList"
              :key="index"
              style="display: inline-block; margin-right: 10px;"
            >
              <el-button
                v-if="item.viewBtn"
                type="text"
                @click="onView(scope.row)"
                class="check-btn"
              >
                查看
              </el-button>
              <el-button
                v-if="item.editBtn"
                type="text"
                @click="onEdit(scope.row)"
                class="edit-btn"
              >
                编辑
              </el-button>
              <el-button
                v-if="item.deleteBtn"
                type="text"
                @click="onDelete(scope.row.id)"
                class="del-btn"
              >
                删除
              </el-button>
              <el-button
                v-if="item.recordBtn"
                type="text"
                @click="onRecord(scope.row)"
                class="check-btn"
              >
                发证记录
              </el-button>
            </div>
            <el-dropdown v-if="scope.row.permissionList.length > 3">
              <el-button type="text" size="medium" class="more-btn mr10">
                更多
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <div
                  v-for="(item1, index1) in scope.row.permissionList.slice(2)"
                  :key="index1"
                >
                  <el-dropdown-item v-if="item1.viewBtn">
                    <el-button
                      type="text"
                      @click="onView(scope.row)"
                      class="check-btn"
                    >
                      查看
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="item1.editBtn">
                    <el-button
                      type="text"
                      @click="onEdit(scope.row)"
                      class="edit-btn"
                    >
                      编辑
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="item1.deleteBtn">
                    <el-button
                      type="text"
                      @click="onDelete(scope.row.id)"
                      class="del-btn"
                    >
                      删除
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="item1.recordBtn">
                    <el-button
                      type="text"
                      @click="onRecord(scope.row)"
                      class="check-btn"
                    >
                      发证记录
                    </el-button>
                  </el-dropdown-item>
                </div>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>

完结!

相关推荐
GDAL7 分钟前
vue3入门教程:ref函数
前端·vue.js·elementui
GISer_Jing16 分钟前
Vue3状态管理——Pinia
前端·javascript·vue.js
好开心3331 分钟前
axios的使用
开发语言·前端·javascript·前端框架·html
Domain-zhuo40 分钟前
Git常用命令
前端·git·gitee·github·gitea·gitcode
菜根Sec1 小时前
XSS跨站脚本攻击漏洞练习
前端·xss
web150854159351 小时前
vue 集成 webrtc-streamer 播放视频流 - 解决阿里云内外网访问视频流问题
vue.js·阿里云·webrtc
m0_748257181 小时前
Spring Boot FileUpLoad and Interceptor(文件上传和拦截器,Web入门知识)
前端·spring boot·后端
桃园码工2 小时前
15_HTML5 表单属性 --[HTML5 API 学习之旅]
前端·html5·表单属性
百万蹄蹄向前冲2 小时前
2024不一样的VUE3期末考查
前端·javascript·程序员
Anlici2 小时前
three.js建立3D模型展示地球+高亮
前端·数据可视化·canvas