Vue+Vuex 实现商品购物车全选/反选,计算数量金额,商品删除

首先,商品列表是v-for 动态获取渲染,使用v-model的双向绑定$store.getters中数据,为了保持选中状态,将数据保存到localStorage中,部分具体代码如下:

li中checkbox代码

<input name="checkbox" value="Item 1" type="checkbox"
 ref="checkbox" @change="checked(item.id,$store.getters.getGoodsChecked[item.id])"
 v-model="$store.getters.getGoodsChecked[item.id]"> 

main.js中Vuex

var store = new Vuex.Store({
    state: { //this.$store.state.xxx
        cart: cart,
        checkAllStatus: checkAllStatus
    },
    mutations: { //this.$store.commit('function',xx)
        addToCart(state, goodsinfo) { //点击加入购物车,保存商品信息
                var flag = false; //假设没有新加入的商品
                state.cart.some(item => {
                    if (item.id == goodsinfo.id) {
                        item.count += parseInt(goodsinfo.count);
                        flag = true;
                        return true;
                    }
                })
                if (!flag) { //添加到购物车
                    state.cart.push(goodsinfo);
                }
                //保存到本地存储
                localStorage.setItem('cart', JSON.stringify(state.cart));
            },
            updateGoodsInfo(state, goodsinfo) { //修改购物车商品数量值
                state.cart.some(item => {
                        if (item.id == goodsinfo.id) {
                            item.count = parseInt(goodsinfo.count);
                            return true;
                        }
                    })
                    //保存最近修改的购物车数据
                localStorage.setItem('cart', JSON.stringify(state.cart));
            },
            deleteStoreCart(state, id) {
                state.cart.some((item, index) => {
                        if (item.id == id) {
                            state.cart.splice(index, 1);
                        }
                    })
                    //保存到本地存储
                localStorage.setItem('cart', JSON.stringify(state.cart));
            },
            //更新选中状态
            updateGoodsChecked(state, info) {
                state.cart.some(item => {
                    if (item.id == info.id) {
                        item.checked = info.checked;
                    }
                })
                localStorage.setItem('cart', JSON.stringify(state.cart));
            },
            //全选/反选切换
            updateGettersGoodsChecked(state, boolean) {
                state.cart.forEach(item => {
                    item.checked = boolean;
                   // console.log('----' + item.checked);

                });
                state.checkAllStatus.status = boolean;


                // state.checkAllStatus = boolean;
                localStorage.setItem('checkAllStatus', JSON.stringify(state.checkAllStatus));

                localStorage.setItem('cart', JSON.stringify(state.cart));
            },

    },
    getters: { //this.$store.getters.xxx
        //获取购物车总数量
        getAllCount(state) {
                var sum = 0;
                state.cart.forEach(item => {
                    sum += item.count;
                })
                return sum;
            },
            //获取购物车的选择状态
            getGoodsChecked(state) {
                var temp = {}
                state.cart.forEach(item => {
                    temp[item.id] = item.checked;
                })

                return temp;
            },
            //获取选中数量和计算商品价格
            getGoodsSumAndTotal(state) {
                var temp = {
                    sum: 0,
                    total: 0
                }
                state.cart.forEach(item => {
                    if (item.checked) {
                        temp.sum += item.count;
                        temp.total += (item.price * 100) * temp.sum / 100;
                    }
                })
                return temp;
            }

    }
})

组件 shopcart.vue 中script 部分

export default {
    data() {
            return {
                cart: '',
                value: [],
                options: ['全选'],
                ischecked: 0,
                checkedSum: 0
                    //checkAllStatus: true
            }
        },
        created() {

        },
        methods: {
            //全选
            checkAll() {
                    var obj = this.$store.getters.getGoodsChecked;
                    this.ischecked = Object.values(obj);
                    this.checkedSum = Object.keys(obj).length;

                    if (this.$refs.checkAll.checked) {
                        for (var i = 0; i < this.ischecked.length; i++) {
                            this.ischecked[i] = true;
                        }
                        this.$store.commit('updateGettersGoodsChecked', true);
                    } else {
                        for (var i = 0; i < this.ischecked.length; i++) {
                            this.ischecked[i] = false;
                        }
                        this.$store.commit('updateGettersGoodsChecked', false);
                    }
                    console.log('选中状态' + this.$refs.checkAll.checked);
                },
                //单个选择
                checked(id, value) {
                    console.log(id + '------' + value);
                    if (!value) {
                        this.$store.state.checkAllStatus = false;
                        localStorage.setItem('checkAllStatus', JSON.stringify(false));
                    }
                    this.$store.commit('updateGoodsChecked', {
                        id, checked: value
                    });
                    //获取商品所有列表的checked状态
                    var obj = this.$store.getters.getGoodsChecked;
                    //将对象的checked值转换存入一个新数组
                    this.ischecked = Object.values(obj);
                    var arr = [];
                    for (let i in this.ischecked) {
                        arr.push(this.ischecked[i]);
                    }
                    //every判断数组的每一项的选中状态
                    var result=arr.every(item => {
                       return item == true;
                    })
                    //赋值给全选按钮
                    if (result) {
                         this.$store.state.checkAllStatus = true;
                    }else{
                         this.$store.state.checkAllStatus = false;
                    }
                    //本地存储状态
                    localStorage.setItem('checkAllStatus', JSON.stringify(result));

                    console.log('所有选中状态:' + result);
                    console.log(arr);

                },
                getnum(num, maxnum) { //定义接收子组件数据的处理方法
                    //赋值给自己data num  数量选择检测
                    // this.num = num;
                    if (num > maxnum) {
                        this.num = maxnum;
                        Toast({
                            message: '该商品最多购买' + maxnum + '件',
                            position: 'middle',
                            duration: 3000
                        });
                    }
                },
                //删除购物车数据store和cart本地数据
                deleteCart(id, index) {
                    this.cart.splice(index, 1);
                    this.$store.commit('deleteStoreCart', id);
                }
        },
        computed: {

        },
        components: {
            cartnumbox
        },
        mounted() {
            //页面加载完毕获取本地存储的cart数据
            this.$nextTick(function() {
                var cart = JSON.parse(localStorage.getItem('cart') || '[]');
                this.cart = cart;
                // var checkAllStatus = JSON.parse(localStorage.getItem('checkAllStatus') || '[]');
                // this.checkAllStatus = checkAllStatus;
                //console.log(this.cart);
            });

        },
        watch: {

        }
}

自此,购物车基本功能完成,页面刷新页可以保持住当前状态

vuex-checkbox.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。