动态"点击" Vue中v-for循环期间的事件

时间:2018-04-05 21:08:42

标签: button dynamic vue.js v-for

我循环遍历一个数组,该数组将多个按钮输出到表格中。我想要动态设置单击该按钮时调用的方法。它正确地从数组中提取其他所有内容,但它没有设置方法(因此单击时按钮不执行任何操作)

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

initSample

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

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

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

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

2 个答案:

答案 0 :(得分:4)

不使用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>

答案 1 :(得分:1)

如果@tony19 的回答不够克莱尔,试试这个。

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