use*_*645 2 dynamic button vue.js v-for
我正在遍历一个数组,该数组将几个按钮输出到一个表中。我想动态设置单击该按钮时调用的方法。它正确地从数组中提取了其他所有内容,但未设置方法(因此,单击按钮时不执行任何操作)
这是我的v-for循环代码:
<tr v-for="button in buttons" :key="button.id">
<td>
<button @click="button.method">{{button.name}}</button>
</td>
</tr>
Run Code Online (Sandbox Code Playgroud)
这是Vue组件的数据对象中的代码
buttons : [
{id : 1, name : 'Button 1', method : 'buttonOne'},
{id : 2, name : 'Button 2', method : 'buttonTwo'},
],
Run Code Online (Sandbox Code Playgroud)
如果我手动设置调用的方法,则一切正常。但是每个按钮都调用相同的方法。而不是“ buttonOne,buttoneTwo等”
<button @click="buttonOne">{{button.name}}</button> //This works but each button has the buttonOne method being called on-click
Run Code Online (Sandbox Code Playgroud)
而不是使用method字段的方法名称,而是指定方法本身:
// method: 'buttonOne' // DON'T DO THIS
method: this.buttonOne
Run Code Online (Sandbox Code Playgroud)
// method: 'buttonOne' // DON'T DO THIS
method: this.buttonOne
Run Code Online (Sandbox Code Playgroud)
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');
}
}
})Run Code Online (Sandbox Code Playgroud)