希望这个问题有意义。我正在使用 Vue JS,并且使用 v-for 循环了一些元素。在每个循环元素 block 内,都有一个按钮和一个 div。在本例中,我的循环运行了三次。这意味着我在每个循环代码块中得到三个按钮以及这三个 div。
当我单击三个按钮之一时,我希望该 block 中的 div 动态接收一个类。然而,就目前情况而言,当我单击三个按钮之一时,该类被添加,但它被添加到循环内的所有三个循环 div 元素中。
如何让当前循环的 div 仅在单击相关按钮时接收特定类,而循环中的其他两个 div 也不会接收该类?
这是迄今为止我自己尝试过的代码:
<template>
<div v-for="(todo, index) in todos" :key="index" class="relative">
<button @click="showDiv">
show div
</button>
<div :class="appear" class="absolute bg-red-500">
<p>{{ todo.text }}</p>
</div>
</div>
</template>
<script>
import {defineComponent} from 'vue'
export default defineComponent({
data() {
return {
appear: 'left-0',
todos: [
{ text: 'Learn Laravel' },
{ text: 'Learn Vue JS' },
{ text: 'Learn Tailwind CSS' },
]
}
},
methods: {
showDiv() {
this.appear = 'left-2/4';
}
}
})
</script>
最佳答案
原因是您使用一个变量appear
来管理所有按钮的状态,而您可以为每个元素维护名为visible
的单独 bool 值
检查下面的工作示例
var app = new Vue({
el: "#app",
data() {
return {
appear: 'left-0',
/*** Change added to below array ***/
todos: [
{ text: 'Learn Laravel', visible: false },
{ text: 'Learn Vue JS', visible: false },
{ text: 'Learn Tailwind CSS', visible: false },
]
}
},
/** Changes added below **/
computed: {
getButtonText() {
return ind => {
return this.todos[ind].visible ? 'hide div': 'show div';
}
},
getClass() {
return ind => {
return this.todos[ind].visible ? 'left-2/4': 'absolute bg-red-500';
}
}
},
methods: {
showDiv(index) {
this.todos[index].visible = !this.todos[index].visible; // Change added
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(todo, index) in todos" :key="index" class="relative">
<button @click="showDiv(index)">
{{getButtonText(index)}} <!-- Change added -->
</button>
<div :class="getClass(index)"> <!-- Change added -->
<p>{{ todo.text }}</p>
</div>
</div>
</div>
关于html - 在 Vue JS 中,如何在单击时将类添加到 v-for 循环内的元素,而不将其添加到每个循环元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70187726/