为什么点击手风琴项目会打开所有项目?

问题描述 投票:1回答:2

我试着将下面的内容实现到我的项目中。我仔细检查了一下,在我的实现中看不到任何缺陷。然而在我的情况下,点击一个项目会打开手风琴的所有项目。为什么?

以下是我的代码。

标记:

<div
  v-for="item in faqItems"
  :key="item.id"
  class="faq-item"
  @click="toggle"
>
  <transition
    name="accordion"
    @before-enter="beforeEnter"
    @enter="enter"
    @before-leave="beforeLeave"
    @leave="leave"
  >
    <div v-show="show" class="faq-item-details">
      <div class="faq-item-details-inner" v-html="item.text">
      </div>
    </div>
  </transition>
</div>

JS:

methods: {
  toggle () {
    this.show = !this.show
  },
  beforeEnter (el) {
    el.style.height = '0'
  },
  enter (el) {
    el.style.height = el.scrollHeight + 'px'
  },
  beforeLeave (el) {
    el.style.height = el.scrollHeight + 'px'
  },
  leave (el) {
    el.style.height = '0'
  }
}
vue.js accordion
2个回答
1
投票

所有手风琴都有相同的show。您可以使用单独的组件(请参阅@Moisés Hiraldo的答案)或使用以下逻辑:

HTML

<div
  v-for="item in faqItems"
  :key="item.id"
  class="faq-item"
  @click="toggle(item.id)"
>
  ...
     <div v-show="showItems[item.id]" class="faq-item-details">

JS

data() {
  return {
    showItems: {}
  }
},
methods: {
  toggle (id) {
     const newVal = !this.showItems[id]
     this.$set(this.showItems, id, newVal)
  }
}

如果您只需要一个已打开的项目 HTML

<div
  v-for="item in faqItems"
  :key="item.id"
  class="faq-item"
  @click="select(item.id)"
>
  ...
     <div v-show="item.id === selectedItemId" class="faq-item-details">

JS

data() {
  return {
    selectedItemId: null
  }
},
methods: {
  select(id) {
    this.selectedItemId = this.selectedItemId !== id ? id : null
  },
},

1
投票

我希望代码在您单击一个时打开所有项目。原因是它们都在同一个组件中,因此它们都访问相同的this.show变量。

您可以将主要组件作为手风琴容器,而不是将每个元素作为单独的组件呈现,每个组件都有自己的this.show变量:

<accordion-item
  v-for="item in faqItems"
  :key="item.id"
  :item="item"
>
© www.soinside.com 2019 - 2024. All rights reserved.