Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event handling dynamic 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 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.

like image 719
Ananda Chowdhury Avatar asked May 13 '17 18:05

Ananda Chowdhury


1 Answers

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.

like image 103
Bert Avatar answered Oct 07 '22 14:10

Bert