RUNR
RUNR

Reputation: 21

How to change the color of an icon on button click in Vue 3?

I'm using Vue 3 for my application. There are 10 persons in the database and each person should be displayed on a card. A user can add any person to his favorite list. Here is the code to render each person;

<div class="card" style="width: 18rem" v-for="(person, key) in people" :key="key">        
          <h5 class="card-title">
            {{ person.name }}
          </h5>
          <div class="card-text">
            <i class="fa-solid fa-envelope"> </i>
            <p class="icon">
              {{ person.email }}
            </p>                   
          </div>
          <p id="card-text">
            <button type="submit" class="btn" @click="favouriteUser(person.id)">
              <i class="fa-solid fa-heart" :class="{ clicked: isClicked }"></i>
            </button>
export default {
  name: "HomeView",
  data: function () {
    return {
      people: [],
      favourites: {},
      isClicked: false,
    };
  },
  methods: {
    favouriteUser: async function (id) {
      try {
        let response = await UserService.favouriteUser({ userId: id });
        response.data = this.favourites;
        this.isClicked = true;
      } catch (error) {
        console.error(error);
      }
    },
  },
};
<style>
.clicked {
  color: red;
}
</style>

The selected user is added to the favorite list. But when the heart icon is clicked all cards' heart icons get red. It needs to get red only for the selected person. How to fix this issue? Thank you.

Upvotes: 0

Views: 796

Answers (2)

Daniel Ahn
Daniel Ahn

Reputation: 67

It looks like response.data = this.favourites; should be this.favourites = response.data. Is that correct?

Upvotes: 0

Simcha
Simcha

Reputation: 17

You need to pass the whole person to the method and modify the isClicked property for THAT person.

 favouriteUser: async function (person) {
      try {
        let response = await UserService.favouriteUser({ userId: person.id });
        response.data = this.favourites;
        person.isClicked = !person.isClicked;
      } catch (error) {
        console.error(error);
      }
    }

The important part is this line: person.isClicked = !person.isClicked;

It basically says: if they are favorite, then unfavorite them. If they are not favorite, then favorite that person.

Upvotes: 1

Related Questions