Event handling dynamic created buttons in Vue.js v-for loop

12,324

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.

Share:
12,324
Ananda Chowdhury
Author by

Ananda Chowdhury

Updated on June 04, 2022

Comments

  • Ananda Chowdhury
    Ananda Chowdhury about 2 years

    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.

  • Ananda Chowdhury
    Ananda Chowdhury about 7 years
    This is exactly what I was looking for. Thank you!