javascript - 在 v-for 列表 : VueJS 中显示元素

标签 javascript vue.js vuejs2

这个问题在这里已经有了答案:





Vue.js - Add class to clicked button

(1 个回答)


2年前关闭。




我有一个显示我所有项目的 v-for,每个项目都有一个面板(用于修改和删除),但是当我单击此按钮以显示我的面板时,它会出现在我的所有项目上。我怎样才能避免这种情况?当我单击修改按钮时,这是同样的事情,修改我的项目的输入出现在每个元素上。

有我的代码:

<div v-for="(comment, index) in comments" :list="index" :key="comment">
   <div v-on:click="show = !show">
      <div v-if="show">
         <button @click="edit(comment), active = !active, inactive = !inactive">
            Modify
         </button>
         <button @click="deleteComment(comment)">
            Delete
         </button>
      </div>
   </div>
   <div>
      <p :class="{ active: active }">
        {{ comment.content }}
      </p>
      <input :class="{ inactive: inactive }" type="text" v-model="comment.content" @keyup.enter="doneEdit">
   </div>
</div>

以及方法和数据:
data() {
  return {
    show: false,
    editing: null,
    active: true,
    inactive: true
  }
},

methods: {
   edit(comment) {
     this.editing = comment
     this.oldComment = comment.content
   },

   doneEdit() {
     this.editing = null
     this.active = true
     this.inactive = true
   }
}

最佳答案

你有同样的show , editing , active , inactive所有项目的状态。因此,如果您更改一项的某些数据属性,它会更改所有项。
有很多方法可以实现您想要的。

最简单的方法是按索引管理数据。
例如:

<div v-on:click="showIndex = index">
  <div v-if="showIndex === index">
  ...
data () {
  return {
    showIndex: null
  ...

这种方法的主要问题 - 您一次只能显示/编辑一个项目。
如果您需要更复杂的逻辑并且想管理多个项目,我建议为您的项目创建一个单独的组件,每个组件都有自己的状态(showediting 等)

关于javascript - 在 v-for 列表 : VueJS 中显示元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59582624/

相关文章:

javascript - 谷歌地图检查多边形是否包含标记

Javascript 命名空间和范围 : need clarification

javascript - HapiJS——以最大内存运行服务器

vue.js - 将数据(正文)附加到 VueJS 中的 $http.delete 事件

javascript - 如何修复谷歌地图中的信息窗口

javascript - 模拟 es6 模块返回工厂函数(moment.js)

javascript - 使用来自 HTML 元素的数据创建 Javascript Blob()。然后将其下载为文本文件

javascript - Vee-validate Validate on blur 防止表单提交

javascript - 子组件是否应该有权访问商店?

javascript - vue 组件中的 d3.js - 如何将鼠标事件挂接到元素?