首页 > 解决方案 > Vue.js - 通过在 v-model 中传递参数来更改嵌套属性

问题描述

我有一个用 v-for 显示的数组“产品”。对于每个产品,都有一个用于将产品添加到对象“订单”的按钮。对象“订单”看起来像

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

当第二次单击该按钮时,我想将数量增加 1。

因此,在 Vuex 中,我传递了单击的对象:

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

到目前为止,一切都很好。我可以在 chrome 开发者工具中看到数量增加。

现在是棘手的事情,我不知道如何做到这一点,虽然这听起来很容易:我想在按钮旁边的输入字段中显示每种产品的数量。问题是我需要像这样在 v-model 中选择的产品:

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

将产品添加到“订单”对象的那一刻,输入字段中显示的数量值为 0,因此 DOM 更新。但是当数量发生变化时,DOM 中没有任何变化。但是,vuex 商店中的数量确实发生了变化。

有没有办法解决这个问题?我尝试使用 :value 而不是 v-model,但同样的问题。

标签: vue.jsvuejs2vue-componentvuexv-model

解决方案


您应该使用this.$set使该更改响应:

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

}

推荐阅读