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

常见写法

通常控制按钮显示与否,会采用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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值