vue3 自定义指令控制按钮权限的操作

502 阅读2分钟

vueauth.png

全局自定义指令

在Vue的模板语法中我们除了使用:v-show、v-for、v-model等,Vue也允许我们来自定义自己的指令。自定义全局指令:app的 directive 方法,可以在任意组件中被使用。

适用业务场景

在后台管理系统中,常常需要针对某个页面的按钮进行权限控制。比如,角色A用户拥有该页面的新增,编辑,删除权限;角色B用户拥有该页面编辑权限。那么对于角色B用户来说,该页面新增,删除按钮应该是不可见的。这就可以用自定义指令来控制按钮的显示和隐藏。当然也可以用if判断,但是这样每个页面都需要写if判断,代码冗余。

实现思路

首先我们创建了3个文件,在utils文件夹下,分别是:auth.ts、directivesAuth.ts、useStorage.ts。auth.ts文件是用来存储权限的,directivesAuth.ts文件是用来自定义指令的,useStorage.ts文件是用来本地存储。

实现步骤

  1. 首先在utils文件夹下创建auth.ts文件,用来存储权限。
// 存储权限数组
let currentAuth: Array<string> = [];
//获取当前全局权限
export function getCurrentAuthority() {
  if (!currentAuth || currentAuth.length < 1) {
    const mAuthority = useStorage.get("demo_authority");
    if (mAuthority) {
      let mArrs = [];
      try {
        mArrs = JSON.parse(mAuthority);
      } catch (e) {
        //
      }
      currentAuth = mArrs;
    }
  }
  return currentAuth;
}
//设置全局权限
export function setCurrentAuthority(mArr: Array<string>) {
  useStorage.set("demo_authority", JSON.stringify(mArr));
  currentAuth = mArr;
}
//判断权限合法性
export function check(authority: string) {
  const current = getCurrentAuthority();
  return current.some(item => authority.includes(item));
}
  1. 在utils文件夹下创建directivesAuth.ts文件,用来自定义指令。
import { App } from "vue";
import { check } from "./auth";

export default {
  install(app: App, options = { name: "auth" }) {
    // 注册全局指令v-auth
    app.directive(options.name || "auth", {
      // mounted 加载完成,可以处理dom元素
      mounted(el: HTMLElement, binding: any) {
        // 判断权限,不通过则移除dom元素
        if (!check(binding.value)) {
          el.parentNode && el.parentNode.removeChild(el);
        }
      }
    });
  }
};
  1. 在main.ts文件中引入并使用自定义指令。
import directivesAuth from "./utils/directivesAuth";

const app = createApp(App);
// 全局使用自定义指令
app.use(store).use(router).use(directivesAuth).mount('#app')
  1. 在登录后,或必要时,调用setCurrentAuthority方法设置权限。我们测试,先在App.vue中设置。
import { defineComponent } from 'vue';
import { setCurrentAuthority } from "@/utils/auth";

export default defineComponent({
  name: 'app',
  setup() {
    let authArr = ['admin', 'user','info'];
    // 设置权限
    setCurrentAuthority(authArr);
  }
});
  1. 在需要使用权限的地方,使用自定义指令v-auth。
<template>
  <div class="about">
    <h1>This is an about page</h1>
    <ul>
      <li v-auth="['admin']">
        admin 权限
      </li>
      <li v-auth="['user']">
        user 权限
      </li>
      <li v-auth="['info']">
        info 权限
      </li>
      <!-- 这个没权限不会出现 -->
      <li v-auth="['demo']">
        demo 权限
      </li>
    </ul>
  </div>
</template>

源码下载:https://gitee.com/leolee18/vue3-project

系列文档

vue3 两种创建方式详解(cli和vite)
vue.config.js/vite.config…
vue3 自动引入自定义组件
vueX vue3自动引入匹配的modules
vue3 自定义指令控制按钮权限的操作
vuex与axios网络请求解耦
移动端rem适配布局