vue.js - Vue js v-for v-bind not unique -
i'm trying create form have select list (fetched api) , user can add items seperate array list. new array rendered via v-for , uses v-model edit additional data.
for example have list of goods/services defined beforehand rendered select option block. user can select 1 of these products , add them invoice. after adding (pushed new array), user must able make additional changes.
<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>
add service method:
addservice() { (var = 0; < this.services.length; i++) { if (this.services[i]._id == this.selectedserviceid) { this.services_goods.push(this.services[i]) break; } } }
and want render list i've pushed into:
<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>
everything fine until add same item twice , try modify price 1 of them - changes price both.
the reason changes price both same object. when insert object array, value in array reference object. have 2 references same object.
each object insert array should newly created, contents copied selected item.
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 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>
Comments
Post a Comment