如何在 Vue 3 中切换类?

huangapple go评论64阅读模式
英文:

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:

&lt;script&gt;
  export default {
    props: {
      images: Array,
    },

    data() {
      return {
        active: false
      }
    }
  } 
&lt;/script&gt;

&lt;template&gt;
  &lt;section class=&quot;flex gap-32 py-32 flex-row item relative&quot;&gt;
    &lt;div class=&quot;grid basis-2/3 gap-x-16 gap-y-20&quot; data-grid&gt;
      &lt;figure v-if=&quot;images&quot; v-for=&quot;(image, index) in images&quot; :key=&quot;index&quot; class=&quot;cursor-zoom-in&quot;&gt;
        &lt;img :src=&quot;image&quot; :key=&quot;index&quot; :class=&quot;{ itsActive: active }&quot; @click=&quot;active = !active&quot;&gt;
      &lt;/figure&gt;
    &lt;/div&gt;
  &lt;/section&gt;
&lt;/template&gt;

答案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=&quot;{ itsActive: activeState[index] }&quot;
@click=&quot;toggleState(index)

huangapple
  • 本文由 发表于 2023年8月4日 03:45:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76831208.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定