How to change style of element in v-for. Vue

Hello, so I have SVG element and when I click, I want to change color for only clicked SVG and not all of them. How can I get this result with Composition API?

example :

<div v-for="something in somethings">

some code here...
 I've got SVG icon imported in this component:
<SvgIcon :class="isClicked? 'fill-red' : 'fill-white"/>


So you should display one <SvgIcon> for each object in somethings? Then you need to put a value in each object to indicate if the user has clicked on it or not, e.g. isClicked: false. Then when the user clicks on the <SvgIcon>, you change it to true, and in the HTML conditionally set the class based on something.isClicked.

So I should send some Id when I click as props to the SVG component? Or how would I indicate which one is clicked in order to change color for only clicked SVGs?

I imagine something like :class="something.isClicked ? 'fill-red' : 'fill-white" would work.

Still changes colors of all the SVG-s

And your code looks like…?

So, here’s how im doing it rn, there is lot of code so I’ll show u shortened version

<div v-for="post in posts" :key="">

///lot of code here //

          :class="isClicked ? 'fill-red-500' : 'fill-white'"

onclick function: 

<script setup>

const isClicked = ref(false);

function handlePostLike(postId) {
  isClicked.value = !isClicked.value;
/// some code here to send http request ///

Now you only have one isClicked boolean. You need to have one for each post. So add one to each post.

Can you show me how?

You have 2 options.

  • Track each post's clicked state against an array of clickedPosts. Then within the loop your class would be :class="clickedPosts[index] ? 'fill-red-500' : 'fill-white'"
  • Create a Post component that can track its own internal isClicked state

I understand that what I need is to determine which post I’m clicking and compare it to something and give some particular class after, but problem I’m facing is that I cant find a way how to do that, not experienced enough and searching doesn’t gave some desired result. If is it possible show me the first way for my code, or any other example.