【发布时间】:2021-07-08 11:55:47
【问题描述】:
我已经使用 Vuex 成功创建了一个购物车,但我还想实现一件事,那就是 toast 消息形式的错误消息。
当用户试图超过产品库存限制时,这将触发。
这是我的代码,看看组件里面的方法,Home.vue:
addToCart(product) {
product.quantity = 1;
this.$store.commit('addToCart', product)
this.$store.commit('totalItems');
this.$store.commit('totalPrice');
}
这一切正常,甚至使用 if 语句来检查用户是否超过限制,到目前为止一切顺利,但这只是我想要显示的消息。
最后,这是我的 store.js 文件:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
products: [],
cart: JSON.parse(localStorage.getItem('cart')) ? JSON.parse(localStorage.getItem('cart')) : [],
totalItems: 0,
totalPrice: 0,
newCartItem: {}
},
actions: {
},
mutations: {
// getProducts(state, products) {
// state.products = products
// },
addToCart ( state, product ) {
let findProduct = state.cart.find(o => o.id === product.id)
if( findProduct ) {
if ( product.quantity + findProduct.quantity > product.units ) {
findProduct.quantity = product.units
//show message
} else {
findProduct.quantity += product.quantity;
findProduct.subtotal = findProduct.quantity * findProduct.price;
}
} else {
state.newCartItem.id = product.id
state.newCartItem.name = product.name;
state.newCartItem.price = product.price;
state.newCartItem.quantity = product.quantity;
state.newCartItem.image = product.product_image[0].image;
state.newCartItem.subtotal = product.price;
state.newCartItem.units = product.units;
state.cart.push(Object.assign({},state.newCartItem))
state.newCartItem = {}
}
localStorage.setItem('cart', JSON.stringify(state.cart));
},
totalItems ( state ) {
state.totalItems = parseInt(state.cart.reduce((total, item) => {
return total + item.quantity;
}, 0))
},
totalPrice ( state ) {
state.totalPrice = state.cart.reduce((total, item) => {
return total + item.subtotal;
}, 0);
},
removeFromCart ( state, product ) {
let findProduct = state.cart.find(o => o.id === product.id)
if ( findProduct ) {
state.cart.pop( this.findProduct );
}
localStorage.setItem('cart', JSON.stringify(state.cart));
},
changeQuantityItem ( state, product ) {
let findProduct = state.cart.find(o => o.id === product.id)
if (findProduct) {
if ( product.quantity > product.units ) {
product.quantity = product.units
} else {
findProduct.quantity = product.quantity;
}
findProduct.subtotal = product.quantity * findProduct.price;
}
localStorage.setItem('cart', JSON.stringify(state.cart));
}
},
getters: {
cart: state => state.cart,
totalItems: state => state.totalItems,
totalPrice: state => state.totalPrice
},
})
我写评论的位置(//show message),我想返回一个toast消息,比如用户不能超过产品的库存。我该怎么做呢?我读过类似你应该使用一个动作的东西,但也许我错了,这可以更容易执行。
任何帮助将不胜感激,在此先感谢!
【问题讨论】: