2017-03-28 10 views
0

私は選択リスト(APIからフェッチ)を持つフォームを作成しようとしています。ユーザーはこのリストから別の配列にアイテムを追加できます。新しい配列はv-forを介してレンダリングされ、v-modelを使用していくつかの追加データを編集します。Vue js v-for v-bindがユニークでない

たとえば、私は選択されたオプションブロックにレンダリングされる事前に定義された商品/サービスのリストを持っています。これでユーザーはこれらの製品の1つを選択し、請求書に追加することができます。追加した後(新しい配列にプッシュされる)、ユーザーはいくつかの追加変更を行うことができなければなりません。

<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つの価格を変更しようとすると、両方の価格が変更されます。

答えて

1

価格が両方とも変更されるのは、それらが同じオブジェクトであるということです。オブジェクトを配列に挿入すると、配列内の値はオブジェクトへの参照になります。同じオブジェクトへの参照が2つあります。

アレイに挿入する各オブジェクトは、選択したアイテムからコピーされた内容で、新しく作成する必要があります。

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)); 
 
    } 
 
    } 
 
});
<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>

+0

この作品、ありがとうございます! –

関連する問題