Search code examples
javascriptvue.jsuikitgetuikit

how to sync multiple UIKit accordions


I'm rendering UIKit accordions dynamically inside table rows and each one contains just one child (li) element. how can I sync these accordions so that when one of them is open, other ones get collapsed? just like the option multiple: false. it's a Vue app (in case you can provide a more specific answer).


Solution

  • This answer is much better and more performant

    i is index of the loop.
    prevAccordionIndex is defined in Vue instance data and initially set to null. It is used to hold the index of previous (last) opened accordion so there's no need to loop through $refs to find the open accordion like previous answer.

    All accordions are initially collapsed (closed).

    methods: {
        handleAccordionShow(index) {
            if (this.prevAccordionIndex !== null) {
                this.$uikit.accordion(this.$refs.categoryAccordion[this.prevAccordionIndex]).toggle(0, false)
                this.prevAccordionIndex = index
            } else {
                this.prevAccordionIndex = index
            }
        },
        handleAccordionHide(index) {
            this.prevAccordionIndex = this.prevAccordionIndex === index ? null : index
        }
    }
    <ul ref="categoryAccordion" @beforeshow="handleAccordionShow(i)" @beforehide="handleAccordionHide(i)" uk-accordion>
      <li>...</li>
    </ul>