Skip to content Skip to sidebar Skip to footer

Toggle Only Accordion Clicked Vue.js

I am building a simple vue accordion, when I click one accordion they all open and that is not the behavior I am after. Is there a way to only open the one clicked? I assumed 'this

Solution 1:

If you want to keep track of which accordion section is open or closed, you need t give each one an index and use that as a tracking tool. As you are creating a list I strongly recommend you use v-for.

Overall your code could do with some refactoring so I rewrote it a bit to give you an example of what you should be aiming for:

<template><divid="accordion"class="accordion-container"><divv-for="(item, index) in items":key="index":class="[
        'accordion',
        { 'is-open': isOpen.includes(index) }
      ]"
    ><divclass="accordion-header" @click="toggleAccordion(index)">
        {{ item.title }}
        <iv-if="!isOpen.includes(index)"class="fal fa-plus"/><iv-elseclass="fal fa-minus"/></div><divclass="accordion-body"><divclass="accordion-content">
          {{ item.text }}
          <strong>{{ item.sub }}</strong></div></div></div></div></template><script>exportdefault {
  name: "trial-page",
  data() {
    return {
      items: [
        {
          title: "Accordion 1",
          text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
          sub: "Pellentesque risus mi"
        },
        {
          title: "Accordion 2",
          text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
          sub: "Pellentesque risus mi"
        },
        {
          title: "Accordion 3",
          text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
          sub: "Pellentesque risus mi"
        }
      ],
      isOpen: []
    };
  },
  methods: {
    toggleAccordion(index) {
      if (this.isOpen.includes(index)) {
        this.isOpen = this.isOpen.filter(i => i !== index);
        return;
      }

      this.isOpen.push(index);
    }
  }
};
</script><style>.accordion:not(.is-open) .accordion-body {
  display: none;
}
</style>

Here is a codepen to test it out: https://codesandbox.io/s/blazing-water-icpxw

You may need to adjust somethings to suit your needs.

Solution 2:

You can have a look at .bind() method:

Bind creates a new function that will have this set to the first parameter passed to bind().

Post a Comment for "Toggle Only Accordion Clicked Vue.js"