3

I'm looping through an array that outputs several buttons into a table. I'm wanting to dynamically set the method that's called when that button is clicked. It is correctly pulling in everything else from the array, but it's not setting the method (so the buttons do nothing when clicked)

Here is my code for the v-for loop:

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

And here is the code within the data object of the Vue component

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

If I manually set the method called, then everything works correctly. But every button calls the same method. Rather than "buttonOne, buttoneTwo, etc"

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

2 Answers 2

11

Instead of using the method name for the method field, specify the method itself:

// 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/[email protected]"></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>

Sign up to request clarification or add additional context in comments.

Comments

1

if @tony19 answer is not Clare enough try this.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.