2

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

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);
}

如您所见,在将 a 添加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运行良好,当我更改.productcart

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

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

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

4

1 回答 1

1

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

JSON.parse(JSON.stringify(this.products[0]))
于 2016-06-14T20:10:08.767 回答