【问题标题】:Vue v-for click not show correcly elementVue v-for点击不正确显示元素
【发布时间】:2019-06-19 10:59:22
【问题描述】:

for` 显示数据库中的数据:

<div v-for="item in resourceList" :key="item.id">
    <input :id="roomData.id" type="checkbox" @click="saveCheckbox">
    <label :for="roomData.id">{{ item.question }}</label>

        //calendar
        <span v-if="active">
            <datepicker v-model="date"></datepicker>
        </span>
        <span v-else id="disableCalendar">Not show calendar</span>
</div>

我的功能点击有问题。例如在页面 v-for 上显示 10 个元素。在每个元素中都会有一个按钮可以点击@click="saveCheckbox"

方法中的功能:

saveCheckbox(e){            
    if(e.target.checked) {
        this.active = true;
    } else {
        this.active = false;
    }
}

在我拥有的数据中:

active = false;

现在当用户点击例如第一个元素按钮时,日历将出现在每个元素中。 如何仅在用户单击的元素中显示日历?

【问题讨论】:

  • this.active = true 和 datepicker 有什么联系?
  • @ChristhoferNatalius this.active 和 datapicker 之间没有连接。我使用v-if="active"true 中的this.active 时显示数据选择器,或者在false 中的this.active 时显示文本“不显示日历”。
  • 啊,我明白你的问题了。 Vucko 的解决方案应该有效。您需要活动数组,并且 saveCheckbox 应该更新活动数组中的元素之一。

标签: vue.js render v-for


【解决方案1】:

active 变量为资源列表中的每个项目共享,您需要为列表中的每个项目创建活动标识符,一种方法是拥有资源列表项目的active 属性。假设您在 resourceList 的每一项中都有 active 属性,您可以执行以下操作。

<div v-for="item in resourceList" :key="item.id">
    <input :id="roomData.id" type="checkbox" @click="saveCheckbox(item)">
    <label :for="roomData.id">{{ item.question }}</label>

        //calendar
        <span v-if="active">
            <datepicker v-model="date"></datepicker>
        </span>
        <span v-else id="disableCalendar">Not show calendar</span>
</div>

还有 saveCheckbox 方法

saveCheckbox(item){            
   item.active = !item.active
}

【讨论】:

    【解决方案2】:

    您需要在循环中存储每个项目的值。使用this.active = true,您只有一个状态可用于循环中的每个项目。

    例子:

    new Vue({
      el: "#app",
      data: {
        isActive: [false, false, false, false]
      },
      methods: {
        toggleActive(index) {
          this.$set(this.isActive, index, !this.isActive[index])
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <div v-for="(active, index) in isActive" :key="index">
        {{ active }} {{ index }}
        <button type="button" @click="toggleActive(index)">Toggle</button>
      </div>
    </div>

    【讨论】:

    • Tkanks,为您解答,但我有一个问题:如果我不知道添加了多少元素用户,如何创建isActive(在数据中)?
    • @michal 将属性添加到您的resourceList 数组中。
    猜你喜欢
    • 2021-02-21
    • 2022-01-23
    • 2019-09-17
    • 2021-03-16
    • 1970-01-01
    • 2019-10-09
    • 2019-05-15
    • 1970-01-01
    • 2022-11-07
    相关资源
    最近更新 更多