0👍
You need to track which item is shown outside of packing-material-category
component (value of openedIndex
) and to pass that value down to components. When value changes in the packing-material-category
component, you emit event change-accordion
, and in your parent component you update value of openedIndex
Try this
In your parent component, add openedIndex: 0
to data
.
If you want everything closed by default, set value to false
.
Update template to pass down the props index
and openedIndex
, so that components know when to show/hide.
<packing-material-category
v-for="(category, index) in packingMaterialCategories"
:key="index"
:index="index"
:openedIndex="openedIndex"
:category="category"
@change-accordion="(newOpen) => openedIndex = newOpen"
>
</packing-material-category>
And the packing-material-category
component could look like this
<template>
<div class="packing-categories">
<div :class="packingCategoryClass">
<h3 class="packing-category__title" @click="toggleAccordion" v-text="category.title" />
<div v-show="index === openedIndex" class="packing-category__content">
<div v-if="category.description" class="packing-category__description" v-text="category.description" />
</div>
</div>
</div>
</template>
<script>
export default {
props: [
'category',
'index', // index of this component
'openedIndex', // which item should be shown/opened
],
data() {
return {
packingCategoryClass: '',
}
},
methods: {
toggleAccordion() {
// Show current item. If already opened, hide current item
let value = this.index === this.openedIndex ? false : this.index;
// notify parent component about the change
this.$emit('change-accordion', value)
}
}
}
</script>
Source:stackexchange.com