Reputation: 89
I'm trying to decrement or increment a cart in Vuex when I click, but the change doesn't reflect until I re-render the component or click "commit" again in the devtools for Vue.
What my store looks like:
state: {
toggleSideBar: false,
cart: [],
},
action:{
incrementCart: ({ commit }, payload) => {
commit("INCREMENT_CART", payload);
},
addToCart: ({ commit, state }, payload) => {
commit("ADD_TO_CART", payload);
},
}
mutation:{
INCREMENT_CART(state, payload) {
let index = state.cart.findIndex((x) => x.id === payload);
state.cart[index].amount += 1;
},
ADD_TO_CART(state, payload) {
let amount = 1;
if (state.cart.length === 0) {
payload.amount = amount;
return state.cart.push(payload);
} else {
if (state.cart.some((cart) => cart.id === payload.id)) {
let index = state.cart.findIndex((x) => x.id === payload.id);
state.cart[index].amount += amount;
} else {
payload.amount = amount;
state.cart.push(payload);
}
}
},
}
computed: {
cartData() {
return this.$store.state.cart;
console.log(this.$store.state.cart);
},
}
In which the value is then passed as props to individual cart
Upvotes: 2
Views: 1180
Reputation: 194
You need to create a getter in your Vuex like so:
getters: {
getCart(state) {
return state.cart;
}
}
And then in your computed you need to call your getter like this:
import { mapGetters } from 'vuex';
export default {
computed: {
...mapGetters(['getCart']);
}
}
And finally in your html tag you need to call your getter like so:
<div v-for="item in getCart">item.quantity</div>
Upvotes: 1