在这里插入图片描述

方案1:method为方法名的字符串

核心代码

 @click="callBack(item.method)"
    callBack(method) {
      this[method]();
    },

完整范例

<template>
  <div class="mainBox">
    <p>{{ msg }}</p>
    <button
      v-for="(item, index) in btnList"
      :key="index"
      @click="callBack(item.method)"
      class="btn"
    >
      {{ item.label }}
    </button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      msg: "我会告诉你,你点击了哪个按钮!",
      btnList: [
        {
          label: "新增",
          method: "add",
        },
        {
          label: "删除",
          method: "del",
        },
      ],
    };
  },
  methods: {
    add() {
      this.msg = "点击了新增按钮!";
    },
    del() {
      this.msg = "点击了删除按钮!";
    },
    callBack(method) {
      this[method]();
    },
  },
};
</script>
<style scoped>
.mainBox {
  padding: 20px;
}
.btn {
  background: #009fe9;
  color: #fff;
  border: none;
  padding: 6px;
  width: 100px;
  border-radius: 4px;
  display: inline-block;
  margin-right: 10px;
}
</style>

方案2:method为函数

核心代码

          method: () => {
            this.add();
          },

完整范例

<template>
  <div class="mainBox">
    <p>{{ msg }}</p>
    <button
      v-for="(item, index) in btnList"
      :key="index"
      @click="item.method"
      class="btn"
    >
      {{ item.label }}
    </button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      msg: "我会告诉你,你点击了哪个按钮!",
      btnList: [
        {
          label: "新增",
          method: () => {
            this.add();
          },
        },
        {
          label: "删除",
          method: () => {
            this.del();
          },
        },
      ],
    };
  },
  methods: {
    add() {
      this.msg = "点击了新增按钮!";
    },
    del() {
      this.msg = "点击了删除按钮!";
    },
  },
};
</script>
<style scoped>
.mainBox {
  padding: 20px;
}
.btn {
  background: #009fe9;
  color: #fff;
  border: none;
  padding: 6px;
  width: 100px;
  border-radius: 4px;
  display: inline-block;
  margin-right: 10px;
}
</style>

Logo

前往低代码交流专区

更多推荐