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 style="width: 18rem" v-for="(person, key) in people" :key="key">
<h5 >
{{ person.name }}
</h5>
<div >
<i > </i>
<p >
{{ person.email }}
</p>
</div>
<p id="card-text">
<button type="submit" @click="favouriteUser(person.id)">
<i :></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.
CodePudding user response:
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.
CodePudding user response:
It looks like response.data = this.favourites;
should be this.favourites = response.data
. Is that correct?