这个问题在这里已经有了答案:
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
...
这种方法的主要问题 - 您一次只能显示/编辑一个项目。
如果您需要更复杂的逻辑并且想管理多个项目,我建议为您的项目创建一个单独的组件,每个组件都有自己的状态(
show
,editing
等)
关于javascript - 在 v-for 列表 : VueJS 中显示元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59582624/