列表渲染中的 Vuex 和反应性

Vuex and reactivity in list rendering

所以我有一个简单的商店:

const state = {
    cart: []
};

这是购物车在有物品时的样子:

[
    {
        id: 1,
        name: 'My first product',
        price: 3,
        quantity: 3
    },
    {
        id: 2,
        name: 'My second product',
        price: 2,
        quantity: 7
    }
]

这是我对这个对象的修改:

ADDPRODUCTTOCART (state,product,quantity) {
    for(var i = 0; i < state.cart.length; i++) {
        if(state.cart[i].id === product.id) {
            state.cart[i].quantity += quantity;
            return ;
        }
    }
    product.quantity = quantity;
    state.cart.push(product);
}

如您所见,在将 product 添加到 cart 时,我首先检查相同的产品是否已在购物车中。如果是,我们更改 quantity 值。如果不是,我设置产品对象的数量 属性,然后将其推送到购物车。

供您参考,以下是触发此突变的操作的编写方式:

export const addProductToCart = ({dispatch}, product, quantity) => {
    dispatch('ADDPRODUCTTOCART', product, quantity);
};

那么,我有一个组件:

export default {
    computed: {
        total() {
            var total = 0;
            for(var i = 0; i < this.cart.length; i++) {
                total += this.cart[i].price * this.cart[i].quantity;
            }
            return total;
        }
    },
    vuex: {
        getters: {
            cart: function (state) {
                return state.cart;
            }
        }
    }
}

total 计算的 属性 运行良好,当我更改 cart 中的 product 对象的数量时,它会自行更新。

但是如果我尝试在 v-for 列表中显示此 quantity 属性,它不会在 quantity 更改时更新:

<li v-for="product in cart" track-by="id">
    productID: {{ product.id }},
    quantity: {{ product.quantity }}
</li>

https://jsfiddle.net/Lgnvno7h/2/

如果你想从组件的data传递数据,你应该移除观察者:

JSON.parse(JSON.stringify(this.products[0]))