I'm attempting to display a list of items in a v-for and toggle their visibility individually.
Initially, I had all the code in one component which caused every element in the loop to open when the button was clicked:
<template>
<div v-for='item in items'>
<button @click="isExpanded = !isExpanded">Toggle specific element</button>
<ul v-show="isExpanded">
<li v-for='subitem in item.subitems'>Sub items</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return: {
isExpanded: false
};
},
};
</script>
I wanted only one item to expand at a time when clicked.
Eventually, I decided to move my ul
list to a separate component.
<template>
<div v-for='item in items'>
<button @click="??">Toggle specific element</button>
<MyListComponent :items="item.subitems"/>
</div>
</template>
<script>
import MyListComponent from '…'
export default {
data() {
return: {
isExpanded: false
}
},
components: {
MyListComponent
}
}
</script>
MyListComponent :
<template>
<ul v-show="isExpanded">
<li v-for='item in items'>Sub items</li>
</ul>
</template>
<script>
export default {
data() {
return: {
isExpanded: false
}
},
props: ['items'],
methods: {
toggle() {
this.isExpanded = !isExpanded;
}
}
</script>
However, I am unable to make the click event on the parent button change the "isExpanded" value in the child component.
Could you please provide guidance on how to achieve this?