【问题标题】:Vuex and reactivity in list rendering列表渲染中的 Vuex 和反应性
【发布时间】:2016-10-15 13:45:15
【问题描述】:

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

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 计算属性运行良好,当我更改cartproduct 对象的数量时,它会自行更新。

但如果我尝试在 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/

【问题讨论】:

标签: javascript vue.js vuex


【解决方案1】:

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

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

【讨论】:

  • 小心,JSON.parseJSON.stringify 可以在 this.products 中使用日期来搞砸
猜你喜欢
  • 2018-06-10
  • 1970-01-01
  • 1970-01-01
  • 2019-12-05
  • 2018-01-07
  • 2020-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多