Answer the question
In order to leave comments, you need to log in
How to clear the state when clicking on the checkout button?
When I click on the checkout button, I call a function where all the data is collected and sent to the server and further processed.
But when the cart is closed, the quantity of goods remains the same, I tried to clean it through localstorage, everything is cleared, but then I cannot add goods to the cart.
As I understand it, you need to call a mutation in store.js from the function, and what should I do to clear the state and then add the goods?
Here is my store.js:
let cart = window.localStorage.getItem('cart')
let cartCount = window.localStorage.getItem('cartCount')
let store = {
state: {
cart: cart ? JSON.parse(cart) : [],
cartCount: cartCount ? parseInt(cartCount) : 0
},
mutations: {
addToCart(state, item) {
let found = state.cart.find(product => product.id == item.id)
if (found) {
found.quantity ++
found.totalPrice = found.quantity * found.price
} else {
state.cart.push(item)
Vue.set(item, 'quantity', 1)
Vue.set(item, 'totalPrice', item.price)
}
state.cartCount++
this.commit('saveCart')
},
removeFromBasket(state, item) {
let index = state.cart.indexOf(item)
console.log(cartCount)
if (index > -1) {
let product = state.cart[index]
state.cartCount -= product.quantity
state.cart.splice(index, 1)
}
this.commit('saveCart')
},
increment(state, index) {
state.cart[index].quantity++
state.cartCount++
state.cart[index].totalPrice = state.cart[index].quantity * state.cart[index].price
this.commit('saveCart')
},
decrement(state, index) {
if (state.cart[index].quantity > 1) {
state.cart[index].quantity--
state.cartCount--
state.cart[index].totalPrice -= state.cart[index].price
}
},
deleteCart() {
// console.log(store.state)
// let newState = {}
// this.state.replaceState(newState)
// console.log(store.state)
// state.replaceState({})
// window.localStorage.setItem('cart', [])
// window.localStorage.setItem('cartCount', 0)
this.commit('saveCart')
},
saveCart(state) {
window.localStorage.setItem('cart', JSON.stringify(state.cart))
window.localStorage.setItem('cartCount', state.cartCount)
}
},
actions: {
INCREMENT_CART_ITEM({commit}, index) {
commit('increment', index)
},
DECREMENT_CART_ITEM({commit}, index) {
commit('decrement', index)
}
}
};
export default store
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question