Is there a way to update the cart in Vuex by clicking on it without having to re-render the component or manually committing again in the Vue devtools?
This is how my store is structured:
- state
state: {
toggleSideBar: false,
cart: [],
},
- Action
action:{
incrementCart: ({ commit }, payload) => {
commit("INCREMENT_CART", payload);
},
addToCart: ({ commit, state }, payload) => {
commit("ADD_TO_CART", payload);
},
}
- mutation
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);
}
}
},
}
- then in my component
computed: {
cartData() {
return this.$store.state.cart;
console.log(this.$store.state.cart);
},
}
In this case, the value is passed as props to individual carts.