Handling events of dynamically created buttons in Vue.js v-for loop

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

<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 array of pets is filled with an 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 color

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

      

Essentially I'm trying to create a pet button where you can toggle the way the array pets use the object. I know why my method is activating all my buttons. Because favorited is not unique to the button and comes from data. So when favorited = true, the "red" class is bound to all of my buttons. My question is, how do I bind the "red" class to the button I click on? I'm relatively new to Vue and this is driving me crazy! Someone please tell me how I can fix this.

+3


source to share


1 answer


Add a favorite property to your favorite items in your pet array. Then use this 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>

      



An example .

If you don't want to change the pet object, here's an alternate path .

+3


source







All Articles