Search code examples
javascriptvue.jsvuex

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.

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!


Solution

  • 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.