uniapp、vue,vuex中state改变,getters不动态改变的完美解决方案!

//想必各位朋友一定经历着,改变state,getters却不改变的痛苦,接下来博主给出解决方案;

//方案很简单,第一步,改变state时,如改变state中的cart属性时,引入vue,使用vue set添加未定义的flag,如下:

import Vue from 'vue'; //一定要引入vue,接下来要使用

//mutations
    AddCartHandle(state, data) { //新增购物车状态
            state.cart.goods.map((item,index) => {
                if (item.id == goods_info.id) {
                    Vue.set(state,'cart',data.count); //使用Vue.set来设置值,getters才会响应,第一个为要设置的值(这里使用的是对象),第二个为第一个值的属性:state.cart,第三个值为改变state.cart最新的数据。
                    Vue.set(item,'flag',!item.flag); //flag 在这里vue会自动为item添加一个flag属性,每次改变值时,改变flag
                }
            });

    },

//getters (重点)
//如获取state中的数据总数
    TotalCount(state) { //计算数据总数
        state.cart.total= 0;
        state.cart.list.forEach((item) => {
            if (  item.flag!=772) {  //这句话中的item.flag才是重点,加个if判断,item中的flag没有这个属性,在上面Vue.set添加了这条属性,AddCartHandle使用时,由于flag都改变了如mutations中(Vue.set(item,'flag',!item.flag); ),getter也会动态更新,flag!=772只是随便写的一个数值,772无实际意义
        Vue.set(state.cart,'count',state.cart.count+item.count;
            }
        })
        return state.cart.count;
    },

猜你喜欢

转载自www.cnblogs.com/uimeigui/p/12146396.html