【问题标题】:Vue JS - How to hide previous dropdown contentVue JS - 如何隐藏以前的下拉内容
【发布时间】:2021-09-12 11:12:33
【问题描述】:

我正在创建一个下拉菜单,问题是单击另一个下拉菜单时我无法隐藏下拉内容

<template>
  <div class="dropdown-container">
    <div
      v-for="(i, index) in contentInfo"
      :key="index"
      @click="showContent(i)"
      class="dropdown"
    >
      <div class="dropdown-title">
        <p>{{ i.text }}</p>
        <div v-show="i.show">
          <p>{{ i.content }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  methods: {
    showContent(i) {
      i.show = !i.show;
    },
  },
  data() {
    return {
      contents: false,
      contentInfo: [
        {
          text: "What is Lorem Ipsum?",
          content:
            "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots ",
          show: false,
        },
        {
          text: "Where can I get some?",
          content:
            "There are many variations of passages of Lorem Ipsum available, but",
          show: false,
        },
      ],
    };
  },
};
</script>

再次,当你点击文本时,会打开一个下拉菜单,但是当你点击另一个文本时,旧菜单不会折磨,我需要旧菜单来折磨

【问题讨论】:

  • 您可以尝试使用onBlur 事件吗?或者如果您需要事件冒泡,您可以使用focusout 事件。

标签: javascript arrays vue.js vuejs2


【解决方案1】:

这是在同一 showContent() 方法中隐藏所有其他下拉列表的问题。您可以将当前索引而不是i 传递给它,以便您可以访问索引进行比较:

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

然后在你的showContent 方法中:

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;
    }
  });
}

如果你想让它简洁,它是一个简单的单行:

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

【讨论】:

    猜你喜欢
    • 2015-10-24
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 2021-03-26
    • 2020-11-02
    • 2016-11-11
    • 1970-01-01
    • 2020-12-02
    相关资源
    最近更新 更多