I have an array of elements, I need to render those elements in to a div and attach different on-click functions to each.
<template>
<div class="container">
<div v-for="option in options" :key="option.id" @click="option.clickFunction">.
{{option}}
</div>
</div>
</template>
<script>
export default{
data(){
return{
options: [
{
id: 1,
text: "option 1",
clickFunction: "function1",
},
{
id: 2,
text: "option 2",
clickFunction: "function2",
},
{
id: 3,
text: "option 3",
clickFunction: "function3",
},
{
id: 4,
text: "option 4",
clickFunction: "function4",
},
{
id: 5,
text: "option 5",
clickFunction: "function5",
},
],
}
}
methods:{
//defining all click functions
}
}
</script>
I have tried the above approach but its not working, is there any way of doing this?
This isn't working for you because each clickFunction property in each object is a string. What is the @click attribute supposed to do with a regular old string? Try
<template>
<div class="container">
<div v-for="option in options" :key="option.id" @click="option.clickFunction">
<!-- I'm guessing you meant option.text here -->
{{option.text}}
</div>
</div>
</template>
<script>
export default{
data(){
return{
// pass functions around instead of strings!
options: [
{
id: 1,
text: "option 1",
clickFunction: this.myUniqueClickHandler,
},
{
id: 2,
text: "option 2",
clickFunction: this.myOtherUniqueClickHandler,
},
// etc.
],
}
}
methods:{
myUniqueClickHandler() {
// ...
},
myOtherUniqueClickHandler() {
// ...
}
}
}
</script>