6

I have a v-for loop where a button is created for each iteration. I'm trying to make a toggle handler where clicking the button will toggle the color of the button. But since the buttons are dynamically created, all of their colors are changing ....

<div class="pets" v-for="pet in pets" :key="pet.id">
    <button class="favorite" v-on:click="toggle">
        <i v-bind:class="[{ 'red' : favorited }, 'material-icons']">favorite</i>
    </button>           
</div>

The pets array is being filled with a http call. My script looks like this:

<script>
export default {
    name: 'home',
    data() {
        return {
            pets: [],
            favorited: false
        }
    },
    methods: {
        toggle: function() {
            this.favorited = !this.favorited;
        }
    },
}

The Style tag just changes the color

<style scoped>
.red {
    color: red;
}

Essentially, I'm trying to created a favorite button where you can toggle favoriting an object from the array pets. I know why my method would activate all my buttons. Since favorited is not unique to a button and coming from the data. So when favorited = true, the class 'red' is bound to all my buttons. My question is how do I bind the class 'red' to just the button I click on? I'm relatively new to Vue and this is driving me nuts lol! Someone please tell me how I can fix this.

1 Answer 1

6

Add a favorited property to your pet objects in the pets array. Then use that property.

<div class="pets" v-for="pet in pets" :key="pet.id">
    <button class="favorite" v-on:click="pet.favorited = !pet.favorited">
        <i v-bind:class="[{ 'red' : pet.favorited }, 'material-icons']">favorite</i>
    </button>           
</div>

Example.

If you didn't want to modify the pet object, then here is an alternate way.

Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was looking for. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.