我有一个v-,用于显示我的所有物品,并且每个物品都有一个面板(用于修改和删除),但是当我单击此按钮以显示我的面板时,它会出现在我的所有物品上。我该如何避免呢?当我单击“修改”按钮时,这是同一件事,用于修改项目的输入出现在每个元素上。
有我的代码:
<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
}
}
答案 0 :(得分:4)
所有项目的状态分别为show
,editing
,active
,inactive
。因此,如果您更改一项的某些数据属性,则全部更改。
有很多方法可以实现您想要的。
最简单的方法是按索引管理数据。 例如:
<div v-on:click="showIndex = index">
<div v-if="showIndex === index">
...
data () {
return {
showIndex: null
...
此方法的主要问题-您一次只能显示/编辑一项。
如果您需要更复杂的逻辑并想管理更多项目,那么我建议您为您的项目创建一个单独的组件,并且每个组件都有自己的状态(show
,editing
等)>
答案 1 :(得分:1)
@NaN的方法适用于一次只打开一个的情况。如果您想同时打开多个控件,则需要跟踪每个单独的元素。现在,您仅将其基于show
。一次只能对所有元素使用true/false
。
这就是您需要做的:
将show
从布尔值更改为数组
data() {
return {
show: [],
editing: null,
active: true,
inactive: true,
}
},
然后,您可以跟踪哪个元素应该具有面板:
<div v-on:click="toggleActive(index)">
方法:
methods: {
toggleActive(index) {
if (this.show.includes(index)) {
this.show = this.show.filter(entry => entry !== index);
return;
}
this.show.push(index);
}
}
最后,您的v-if
变为:
<div v-if="show.includes(index)">