4

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!

8
  • 1
    Hello Alexander, and welcome to SO. Try moving the invocation of $store.getters.getCart to a computed function in the parent component. Commented Dec 16, 2018 at 14:46
  • Thanks @andrewhl! Yep tried that just now, no change, still not updating :( Commented Dec 16, 2018 at 14:49
  • do you have some warnings or errors in browser console Commented Dec 16, 2018 at 15:01
  • Nope, no errors or warnings @BoussadjraBrahim Commented Dec 16, 2018 at 15:08
  • @AlexanderDahlberg i tried out your example here and it works, you could add additional code and fork it and give me the link Commented Dec 16, 2018 at 15:26

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.