Search code examples
vue.jsvuejs2vue-componentvuexv-model

Vue.js - change nested property by passing a parameter in v-model


I've got an array 'products' displayed with v-for. For each product there is a button to add a product to an object 'order'. Object 'order' looks like

order: {
  products: [{
    quantity: 0,
    otherProperties
  }]
}

When clicked a second time on that button, I want to increase the quantity with 1.

So, in Vuex where I pass the clicked object:

increaseQuantity(state, product){
  state.order.products.find((orderProduct)=>{
    return product.id === orderProduct.id
  }).quantity++;

So far so good. I can see the quantity increase in the chrome developer tool.

Now the tricky thing, and I've no idea how to accomplish this, although it sounds easy: I want to show the quantity of each product in an input field next to the button. Problem is that I need the selected product in the v-model like this:

<div v-for="product in products" :key="product.id">
  <input v-model="order.products.find((orderProduct)=>{
    return product.id === orderProduct.id
  }).quantity" />
</div>

The moment the product is added to the 'order' object, the quantity value of 0 is displayed in the input field, so the DOM updated. But nothing changes in the DOM when the quantity changes. However, the quantity did change in the vuex store.

Is there a way to solve this? I tried with :value instead of v-model, but same problem.


Solution

  • You should use this.$set to make that change reactive :

    increaseQuantity(state, product){
      let index= state.order.products.findIndex((orderProduct)=>{
        return product.id === orderProduct.id
      })
    state.order.products.quantity++;
    this.$set(state.order.products,index,state.order.products[index])
    
    }