Vuejs and Vuex not rendering updated array

Viewed 1957

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.

ShoppingCart.vue (Parent)

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

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

Imported props:
props: ['item', 'loopIndex']

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!

2 Answers

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.

How I solved it, simply added the Quantity attribute to my database table and set it by default to 1.

You could use Vue.set to set a new object property. 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 (e.g. this.myObject.newProperty = 'hi').

Related