[Vuejs]-Vue JS – How to hide previous dropdown content

1πŸ‘

βœ…

It’s a matter of hiding all other dropdowns in the same showContent() method. You can pass the current index instead of i into it, so that you have access to the index for comparison:

<div
  v-for="(i, index) in contentInfo"
  :key="index"
  @click="showContent(index)"
  class="dropdown"
>

Then in your showContent method:

showContent(currentIndex) {
  this.contentInfo.forEach((entry, index) => {
    // Toggle current dropdown
    if (index === currentIndex) {
      entry.show = !entry.show;
    } else {
      // Hide all other dropdowns
      entry.show = false;
    }
  });
}

If you want to make it concise, it is a simple one-liner:

showContent(currentIndex) {
    this.contentInfo.forEach((entry, index) => entry.show = (index === currentIndex ? !entry.show : false));
}

Leave a comment