I have set some buttons
and I want to create them using a v-for
Every button
has an event
this is my template
code
<button v-for="(btn,i) in btns" :key="i" @click="btn.action">
{{btn.text}}
</button>
and this is my script
section
btns= [
{ text:'print', action: 'print()' } ,
{ text:'another action', action: 'anOtherMethod()' },
]
But I have an error
So, how can I solve this ?
CodePudding user response:
Try to create another method to handle the button click events like:
<button v-for="(btn,i) in btns" :key="i" @click="handleClick(btn.action)">
{{btn.text}}
</button>
and remove the ()
from the methods definitions :
btns:[
{text:'print' , action :'print' } ,
{text:'another action' , action :'anOtherMethod' } ,
]
and finally add the handler method that runs the dynamic method using the brackets accessor :
methods:{
handleClick(actionName){
this[actionName]()
},
anOtherMethod(){
....
}
}
CodePudding user response:
try it.
<template>
<button v-for="(btn, i) in btns" :key="i" @click="btn.action">
{{btn.text}}
</button>
</template>
<script>
export default {
data () {
return {
btns: [
{text:'print' , action: this.print() } ,
{text:'another action' , action: this.anOtherMethod() } ,
]
}
},
methods: {
goInit () {
// add print statements
},
anOtherMethod() {
// add anOtherMethod statements
},
}
}
</script>