简体   繁体   English

Vuejs 和 Vuex 没有渲染更新的数组

[英]Vuejs and Vuex not rendering updated array

I'm trying to update the quantity property in a Vuex array called "cartItems", however it doesn't update it with the v-for loop.我正在尝试更新名为“cartItems”的 Vuex 数组中的数量属性,但是它不会使用 v-for 循环更新它。

ShoppingCart.vue (Parent) ShoppingCart.vue(父)

<div class="cart_row_container">
 <CartItem v-for="(item, index) in $store.getters.getCart"
  :item="item"
  :loopIndex="index"
  :key="item.id"
 />
</div>

CartItem.vue (child) CartItem.vue (子)

<div class="item_row">
 <h4 class="quantity_text">{{item.quantity}}</h4>
</div>

Imported props:进口道具:
props: ['item', 'loopIndex']道具:['item', 'loopIndex']

Vuex: Vuex:

state:{
    cartItems: []
},
mutations:{
 changeQuantity(state, data){ 
        let newQuantity = state.cartItems[data.index]
        newQuantity.quantity += data.value
        this._vm.$set(state.cartItems, data.index, newQuantity)
    }
},

getters:{
    getCartLenght: state => {
        return state.cartItems.length
    },
    getCart: state => {
        return state.cartItems
    }
}

Thanks!谢谢!

Okay, so for some reason when ever you have an object and want to add a key to it and the object has already been made Vue and Vuex won't recognize that key of the object as reactive, so even though you are updating the value it won't re-render the DOM.好的,所以由于某种原因,当你有一个对象并想要向它添加一个键并且对象已经被 Vue 和 Vuex 识别为反应对象时,即使你正在更新值它不会重新渲染 DOM。

How I solved it, simply added the Quantity attribute to my database table and set it by default to 1.我如何解决它,只需将 Quantity 属性添加到我的数据库表中并将其默认设置为 1。

You could use Vue.set to set a new object property.您可以使用Vue.set设置新的对象属性。 This method ensures the property is created as a reactive property.此方法可确保将属性创建为反应属性。

Usage :用法

Adds a property to a reactive object, ensuring the new property is also reactive, so triggers view updates.将属性添加到响应式对象,确保新属性也是响应式的,因此会触发视图更新。 This must be used to add new properties to reactive objects, as Vue cannot detect normal property additions (eg this.myObject.newProperty = 'hi').这必须用于向反应对象添加新属性,因为 Vue 无法检测到正常的属性添加(例如 this.myObject.newProperty = 'hi')。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM