Well, I hit a brick wall with the "Add to favorites" feature with Vue/Vuex. What I am trying to accomplish is to be able to add a beer to favorites, and so the icon recognizes when the selected(specific) beer has been added to the favorites array, and the icon should get a dynamic class applied when it happens.
The part where I added dynamic class(:class) - This should change depending when the certain beer is added to favorites, and the class .favorites should be applied. I need to know how should I set up this so I can compare selected beer to the beer id added to favorites array in the store and display my dynamic class.
To summarize: When the heart button is clicked, the ID is added to favorites array. How to compare this ID from the array with the favorited store object which is a boolean value, and to apply the dynamic class on the front-end?
This is my code so far:
**store.js**
export default new Vuex.Store({
state: {
beers: [],
favorites: [],
favorited: false
},
getters: {
IS_FAVORITE: state => {
return id => {
state.favorites.find(favorite => favorite.id === id);
}
}
},
mutations: {
SET_BEERS: (state, beers) => {
state.beers = beers
},
TOGGLE_FAVORITE: (state, payload) => {
state.beers.find(beer => beer.id === payload);
state.favorites.push(payload)
state.favorited = !state.favorited;
},
},
actions: {
loadBeers({ commit }) {
axios
.get("https://api.punkapi.com/v2/beers?page=1&per_page=15&ibu_gt=30")
.then(response => response.data)
.then(beers => {
commit('SET_BEERS', beers)
})
},
toggleFavorite: (context, payload) => {
context.commit("TOGGLE_FAVORITE", payload);
}
}
})
**BeerModal.vue**
<template>
<b-modal
id="beerModal"
hide-footer
tabindex="-1"
role="dialog"
aria-labelledby="exampleModalCenterTitle"
aria-hidden="true"
>
<div class="modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<button
id="favorite"
class="heart-outline"
@click="toggleFavorite(data.id)"
:class="{ favorited: toggleFavorite === true }"
>♡</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xl-6 col-md-6">
<img class="beer-modal-img img-fluid" :src="data.image_url" alt="beer">
</div>
<div class="col-xl-6 col-md-6 beer-modal-container pt-4">
<h4 class="beer-modal-header d-none d-sm-block">{{ data.name }}</h4>
</div>
</div>
</div>
</div>
</div>
</b-modal>
</template>
<script>
export default {
name: "BeerModal",
props: ["data"],
methods: {
toggleFavorite: function(id) {
this.$store.dispatch("toggleFavorite", id);
}
},
computed: {
isFavorite: function() {
return this.$store.getters.IS_FAVORITE;
}
}
};
</script>
<style scoped>
.favorited {
text-decoration: none;
color: rgba(255, 0, 0, 0.466);
</style>
Comments
Post a Comment