javascript - v-for 和状态管理问题

标签 javascript vue.js nuxt.js

我有一个用 v-for 渲染的项目列表。我希望每个项目都有一个“?”可单击以显示包含该特定项目的描述的模式。我现在的问题是当“?”单击后,它会显示 v-for 中每个项目的模态。我该如何解决这个问题?

<div
  v-for="(item, index) in items"
  :key="index"
>
  <div>
    {{ item.name }}
    <div>
      <span @click="itemModal = true">    
        ?
      </span>
      <div v-show="itemModal">
        {{ item.description }}
        <button @click="itemModal = false">
          Close modal
        </button>
      </div>
    </div>
  </div>
</div>

export default {
  data() {
    return {
      itemModal: false
    }
  }
}

最佳答案

您的 itemModal 属性当前与所有项目共享,因此您需要为每个项目提供一个模式状态。

例如。您可以创建一个 toggle 方法来更新模态状态的array:

<div
  v-for="(item, index) in items"
  :key="index"
>
  <div>
    {{ item.name }}
    <div>
      <span @click="toggle(index)">    
        ?
      </span>
      <div v-show="itemModal[index]">
        {{ item.description }}
        <button @click="toggle(index)">
          Close modal
        </button>
      </div>
    </div>
  </div>
</div>

export default {
  data() {
    return {
      itemModal: []
    }
  },
  methods: {
    toggle(index) {
      this.$set(this.itemModal, index, !this.itemModal[index])
    }
  }
}

注意:数组(或对象)在深度上不具有反应性,因此我们必须使用 Vue.$set (参见 docs )

关于javascript - v-for 和状态管理问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61499648/

相关文章:

javascript - Github 操作 - 达到堆限制分配失败

Javascript - 如何在代码中设置高度时手动降低 Chrome 中的文本区域高度?

javascript - 静态导入适用于 nuxt.config.js,但不适用于组件

css - 使用 vue/nuxt 将样式属性附加到所有( anchor )元素

javascript - 使用 axios 和 nuxt 的服务器和客户端 API 调用的不同 baseURL

asp.net - 在不支持 javascript 的浏览器中使用 ASP.NET

javascript - DOM就绪 : 'kendo' is undefined

vue.js - 在 Vue Js 中创建交互式时间轴

javascript - 导航时出现 VUE 错误 : Discarded invalid param(s) "recordIds", "datasources"

vue.js - Vue忽略数据重复