Reputation: 75
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
Upvotes: 3
Views: 4692
Reputation: 85
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},
],
}
}}
Upvotes: 1
Reputation: 138216
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>
Upvotes: 11