天天看點

vue實戰--v-for 周遊渲染按鈕的兩種實作方案(重點:按鈕點選事件的綁定技巧)

vue實戰--v-for 周遊渲染按鈕的兩種實作方案(重點:按鈕點選事件的綁定技巧)

方案1:method為方法名的字元串

核心代碼

="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>      

繼續閱讀