英文:
How to toggle class in vue 3?
问题
我正在尝试在Vue 3中使用对象语法,在单击时切换CSS类,但这样做会使HTML块中的每个项目都获得该类。我只想让被点击的那个获得它。我该怎么做?(images只是一个渲染为URL的数组)
代码:
<script>
export default {
props: {
images: Array,
},
data() {
return {
active: false
}
}
}
</script>
<template>
<section class="flex gap-32 py-32 flex-row item relative">
<div class="grid basis-2/3 gap-x-16 gap-y-20" data-grid>
<figure v-if="images" v-for="(image, index) in images" :key="index" class="cursor-zoom-in">
<img :src="image" :key="index" :class="{ itsActive: active }" @click="active = !active">
</figure>
</div>
</section>
</template>
希望这对你有帮助。
英文:
I'm trying in vue 3, using the object syntax to toggle a css class on click, but when doing so every item in that html block gets the class. I only want the one thats clicked to get it. How can i do so? (images is an array simply of urls that renders as its supposed to)
Code:
<script>
export default {
props: {
images: Array,
},
data() {
return {
active: false
}
}
}
</script>
<template>
<section class="flex gap-32 py-32 flex-row item relative">
<div class="grid basis-2/3 gap-x-16 gap-y-20" data-grid>
<figure v-if="images" v-for="(image, index) in images" :key="index" class="cursor-zoom-in">
<img :src="image" :key="index" :class="{ itsActive: active }" @click="active = !active">
</figure>
</div>
</section>
</template>
答案1
得分: 0
你可以创建一个与图像长度相同的不同数组,这样你可以使用特定的索引来切换数组的任何值,该索引就是你的图像索引。
data() {
return {
activeState: new Array(this.images.length).fill(false)
}
}
创建一个toggleState函数来切换状态。
methods: {
toggleState(index) {
this.activeState[index] = !this.activeState[index];
}
}
然后更改你的类和图像的点击函数,如下所示。
:class="{ itsActive: activeState[index] }"
@click="toggleState(index)"
英文:
You can create a different array which is of same length as of images, so that you can toggle any value of array using particular index which is your image index
data() {
return {
activeState: new Array(this.images.length).fill(false)
}
}
Create one toggleState function to toggle the state
methods: {
toggleState(index) {
this.activeState[index] = !this.activeState[index];
}
}
And change your class and click function for the image like this
:class="{ itsActive: activeState[index] }"
@click="toggleState(index)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论