Reputation: 3096
I have created a simple accordion as the bootstrap-vue version was over complicated for my needs
<template>
<div>
<li class="nav-item" v-for="(item, index) in items" @click="toggleItem(index)"">
<a class="nav-link collapsed" href="#">
<i class="fas fa-fw fa-folder"></i>
<span>{{item.text}}</span>
</a>
<transition name="slide">
<div v-if="isActive === index" class="item-active">
<div class="bg-white py-2 rounded">
<h6 class="collapse-header">Custom Components:</h6>
<a class="collapse-item" href="buttons.html">Buttons</a>
<a class="collapse-item" href="cards.html">Cards</a>
</div>
</div>
</transition>
</li>
</div>
</template>
<script>
export default {
data () {
return {
items: [
{ text: "Page" },
{ text: "Page 2" }
],
isActive: null
}
},
methods: {
toggleItem(index) {
this.isActive = index;
},
}
};
</script>
It opens and closes the other divs when I click the link, however I can't close and already opened div.
How can I fix the code so I can open and close the same div?
Upvotes: 4
Views: 3991
Reputation: 1768
FYI, there is an extra double quotes ("
) after the @click
on the li
.
Refactor toggleItem
to:
toggleItem(index) {
this.isActive = (this.isActive === index) ? null : index;
}
This will set isActive
to null if index
matches isActive
, otherwise set isActive
to index
.
Upvotes: 0
Reputation: 10324
In your toggle method you need to set this.isActive
to null
if the same item is clicked again.
methods: {
toggleItem(index) {
this.isActive = this.isActive === index ? null : index;
},
}
Upvotes: 5