Vue / uniapp cart.js购物车

发布时间 2023-06-21 22:04:41作者: valeb
 

 

const cart = {
    namespaced: true,
    state: { 
        //{"store_id":"","goods_id":"", "goods_name":"", "goods_price":"", "goods_count":"", "goods_small_logo":"", "goods_state":""}
        cart: []
    },
    mutations: {
        add(state, goods) {
            let good = state.cart.find(s => s.store_id == goods.store_id && s.goods_id == goods.goods_id)
            if (good) {
                good.goods_count = goods.goods_count;
            } else {
                state.cart.push(goods);
            } 
            uni.setStorageSync("cart", state.cart)
        },
        sub(state, goods) {
            if (goods.goods_count === 0) {
                var index = state.cart.findIndex(s => s.store_id == goods.store_id && s.goods_id == goods.goods_id);
                state.cart.splice(index, 1);
            } else {
                let good = state.cart.find(s => s.store_id == goods.store_id && s.goods_id == goods.goods_id)
                if (good) {
                    good.goods_count = goods.goods_count;
                }
            } 
            uni.setStorageSync("cart", state.cart)
        }
    },
    actions: {

    },
    getters: { 
        getStoreCount: (state) => (store_id) => {
            var items = state.cart.filter(s => s.store_id == store_id)
            let count=0;
            items.forEach(s => {
                count += s.goods_count;
            })
            return count;
        } 
    },
}
export default cart

 

 

this.$store.getters['cart/getStoreCount'](model.store_id);