通过自定义指令控制按钮权限

常见写法

通常控制按钮显示与否,会采用v-if或者v-show来控制,可能会写成以下形式,在通过动态的改变 active 变量的值,控制按钮的显示状态,

<template>
  <div>
    <button v-if="(active = '1')">按钮一</button>
    <button v-else-if="(active = '2')">按钮二</button>
    <button v-else-if="(active = '3')">按钮三</button>
    <button v-else-if="(active = '4')">按钮四</button>
    <button v-else="(active = '6')">按钮五</button>
  </div>
</template>
<script lang="ts" setup>
  import { ref } from "vue";

  const active = ref("1"); // 此时页面显示 按钮一
</script>

进一步优化代码,第二种形式也有可能会通过一个集合遍历的方式去渲染,减少组件的重复编写,因为v-forv-if不建议作用于同一个组件上,因此包裹了一层 template 组件

<template>
  <template v-for="(item, index) in btns">
    <!-- 此时仅显示 按钮一 -->
    <button v-if="item.key == active">{{ item.label }}</button>
  </template>
</template>
<script lang="ts" setup>
  import { ref } from "vue";

  const active = ref("1");
  const btns = ref([
    { key: "1", label: "按钮一" },
    { key: "2", label: "按钮二" },
    { key: "3", label: "按钮三" },
    { key: "4", label: "按钮四" },
    { key: "5", label: "按钮五" },
  ]);
</script>

自定义指令小试牛刀

<template>
  <div>
    <span v-color="'red'">测试自定义指令-这段文字将会是红色的</span>
  </div>
</template>
// main.ts
import { createApp } from "vue";
import App from "./App.vue";

const app = createApp(App);
app.directive("color", (el, binding) => {
  el.style.color = binding.value;
});

最终版本通过自定义指令来控制多个按钮的权限操作

<template>
  <div>
    <!-- <button v-display-key="'1'">按钮一</button>
    <button v-display-key="'2'">按钮二</button>
    <button v-display-key="'3'">按钮三</button>
    <button v-display-key="'4'">按钮四</button>
    <button v-display-key="'5'">按钮五</button> -->

    <!-- 优化 -->
    <!-- 此时会显示 按钮二、按钮四 -->
    <template v-for="(item, index) in btns">
      <button v-display-key="item.key">{{ item.label }}</button>
    </template>
  </div>
</template>
<script lang="ts" setup>
  const btns = ref([
    { key: "1", label: "按钮一" },
    { key: "2", label: "按钮二" },
    { key: "3", label: "按钮三" },
    { key: "4", label: "按钮四" },
    { key: "5", label: "按钮五" },
  ]);
</script>
// main.ts
import { createApp } from "vue";
import App from "./App.vue";

const app = createApp(App);

app.directive("display-key", (el, binding) => {
  let displayKey = binding.value;
  if (displayKey) {
    let hasKey = checkArray(displayKey);
    if (!hasKey) {
      el.parentNode && el.parentNode.removeChild(el);
    }
  } else {
    throw new Error("need a key value");
  }
});

function checkArray(key) {
  let arr = ["2", "4", "6", "8"]; // 需要显示的 按钮的key值
  return arr.indexOf(key) > -1;
}
posted @ 2023-07-12 14:34  Echoyya、  阅读(110)  评论(0编辑  收藏  举报