Vue js v-for v-bind并不是唯一的

时间:2017-03-28 13:52:39

标签: vue.js v-for

我尝试创建一个表单,其中有一个选择列表(从API获取),用户可以从此列表中将项目添加到单独的数组中。新数组也通过v-for呈现,并使用v-model编辑一些其他数据。

例如,我有一个预先定义的商品/服务列表,这些商品/服务将被呈现到选择选项块中。现在,用户可以选择其中一种产品并将其添加到发票中。添加(推送到新阵列)后,用户必须能够进行一些额外的更改。

<select class="form-control" v-model="selectedServiceId">
    <option v-for="service in services" :value="service._id">{{service.name}}</option>
</select>

<button type="button" class="btn btn-primary" v-on:click="addService">Add</button>

添加服务方法:

addService() {
    for (var i = 0; i < this.services.length; i++) {
      if (this.services[i]._id == this.selectedServiceId) {
        this.services_goods.push(this.services[i])
        break;
      }
    }
  }

现在我要渲染我已推入的列表:

<ul>
          <li v-for="(item, key) in services_goods">
            <span>{{item.name}}</span>
            <label for="itemPrice">Price €
              <input id="itemPrice" v-model="item.price">
            </label>
            <label for="itemQty">Quantity
              <input type="number" min="1" id="itemQty" v-model="item.quantity">
            </label>
            <div>
              <button type="button" v-on:click="removeService(item._id)">X</button>
            </div>
          </li>
        </ul>

一切都很好,直到我添加相同的项目两次并尝试修改其中一个的价格 - 它改变了两者的价格。

1 个答案:

答案 0 :(得分:1)

它改变两者价格的原因是它们是同一个对象。将对象插入数组时,数组中的值是对象的引用。您有两个对同一对象的引用。

您应该新创建插入数组的每个对象,并从所选项目中复制内容。

&#13;
&#13;
new Vue({
  el: '#app',
  data: {
    selectedServiceId: null,
    services: [{
        _id: 1,
        price: 1,
        quantity: 1,
        name: 'First'
      },
      {
        _id: 2,
        price: 2,
        quantity: 2,
        name: 'Second'
      }
    ],
    services_goods: []
  },
  methods: {
    addService() {
      const foundGood = this.services.find((s) => s._id == this.selectedServiceId);

      // Object.assign copies an object's contents
      this.services_goods.push(Object.assign({}, foundGood));
    }
  }
});
&#13;
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<div id="app">
  <select class="form-control" v-model="selectedServiceId">
    <option v-for="service in services" :value="service._id">{{service.name}}</option>
</select>

  <button type="button" class="btn btn-primary" v-on:click="addService">Add</button>
  <ul>
    <li v-for="(item, key) in services_goods">
      <span>{{item.name}}</span>
      <label for="itemPrice">Price €
              <input id="itemPrice" v-model="item.price">
            </label>
      <label for="itemQty">Quantity
              <input type="number" min="1" id="itemQty" v-model="item.quantity">
            </label>
      <div>
        <button type="button" v-on:click="removeService(item._id)">X</button>
      </div>
    </li>
  </ul>
</div>
&#13;
&#13;
&#13;

相关问题