首页 > javascript > 如何同步多个UIKit手风琴

如何同步多个UIKit手风琴 (how to sync multiple UIKit accordions)

问题

我在表行中动态渲染UIKit手风琴,每个手风琴只包含一个child(li)元素。我怎样才能同步这些手风琴,这样当其中一个手风琴开启时,其他手风琴会崩溃?就像选项一样multiple: false。它是一个Vue应用程序(如果您可以提供更具体的答案)。

解决方法

这个答案更好,更高效

i是循环的索引。
prevAccordionIndex在Vue实例数据中定义并初始设置为null。它用于保存前一个(最后一个)打开的手风琴的索引,所以没有必要循环$refs找到像前一个答案一样的开放式手风琴。

所有手风琴最初都会倒塌(关闭)。

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>


问题

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).

解决方法

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>

相似信息