在v-for循环中定位特定索引

时间:2019-11-14 03:01:52

标签: javascript vue.js

我目前正在VueJS中构建一个Crud应用程序,需要在数据库中执行更新操作。

我按如下所示提取集合中的所有文档:

<div class="events" v-for="(event, index) in GETEVENTS" :key="index">
  <ul class="list">
    <li>Name: <strong v-if="!change">{{event.name}}</strong><input v-else v-model="event.name"></li>
    <li>Location: <strong v-if="!change">{{event.location}}</strong><input v-else v-model="event.location"></li>
    <li>Capacity: <strong v-if="!change">{{event.qty}}</strong><input v-else v-model="event.qty"></li>
    <li>Price: <strong v-if="!change">${{event.price}}</strong><input v-else v-model="event.price"></li>
    <li>Description: <strong v-if="!change">{{event.description}}</strong><textarea v-else v-model="event.description"></textarea></li>
  </ul>
  <div class="actions">
    <button class="edit" @click="change = !change">Edit</button>
    <button class="delete" @click.prevent="DELETEEVENT(event._id)">Delete</button>
  </div>
</div>

因此元素以列表格式显示,并且在列表中我添加了仅在变量changetrue时显示的输入。

但是,由于该变量是全局变量,因此将显示所有数组项的所有输入。如何使用这种方法定位一个特定的数组项?

我的删除功能非常完美。是更新给我带来了问题。

如果更容易/更好,我愿意接受其他方法。

感谢您阅读。

1 个答案:

答案 0 :(得分:0)

change变量从布尔值更改为要编辑的event._id的表示形式。

data: () => ({
  change: null // start with null,
  GETEVENTS: [] // or whatever you currently have
})

然后通过您的编辑按钮设置该ID

<button class="edit" @click="change = event._id">Edit</button>

通过将changeevent._id比较来切换输入

<strong v-if="event._id = change">

最后,您将event._id用作:key绑定,以使Vue更好地跟踪其处理的对象

<div class="events" v-for="event in GETEVENTS" :key="event._id">

如果您开始对事件列表进行排序或过滤,这将特别有用。