Vue 中 v-for 循环期间的动态 "on click" 事件

Dynamic "on click" events during v-for loop in Vue

我正在遍历一个将几个按钮输出到 table 的数组。我想动态设置单击该按钮时调用的方法。它正确地从数组中提取其他所有内容,但它没有设置方法(因此按钮在单击时什么都不做)

这是我的 v-for 循环代码:

<tr v-for="button in buttons" :key="button.id">
   <td>
      <button @click="button.method">{{button.name}}</button>
   </td>
</tr>

下面是 Vue 组件数据对象中的代码

 buttons : [
            {id : 1, name : 'Button 1', method : 'buttonOne'},
            {id : 2, name : 'Button 2', method : 'buttonTwo'},
        ],

如果我手动设置调用的方法,那么一切正常。但是每个按钮都调用相同的方法。而不是 "buttonOne, buttoneTwo, etc"

<button @click="buttonOne">{{button.name}}</button> //This works but each button has the buttonOne method being called on-click

不使用 method 字段的方法名称,而是指定方法本身:

// method: 'buttonOne'  // DON'T DO THIS
method: this.buttonOne

new Vue({
  el: '#app',
  data() {
    return {
      buttons : [
        {id : 1, name : 'Button 1', method : this.buttonOne},
        {id : 2, name : 'Button 2', method : this.buttonTwo},
      ],
    };
  },
  methods: {
    buttonOne() {
      console.log('buttonOne');
    },
    buttonTwo() {
      console.log('buttonTwo');
    }
  }
})
<script src="https://unpkg.com/vue@2.5.13"></script>

<div id="app">
  <table>
    <tr v-for="button in buttons" :key="button.id">
       <td>
          <button @click="button.method">{{button.name}}</button>
       </td>
    </tr>
  </table>
</div>

如果@tony19 的回答不够清晰,试试这个。

export default {
    name: 'app',
    data() {
        return {
          buttons : [
            {id : 1, name : 'Button 1', method : this.buttonOne},
            {id : 2, name : 'Button 2', method : this.buttonTwo},
          ],
}
}}