我正在计算估算成本。选择产品会获取有关产品的详细信息,并在输入框中显示其说明和价格。然后在单击添加按钮时,将出现另一个选择的新行。但问题是新行与旧行数据一起出现。更改单行会影响所有其他行。到目前为止,这是我的代码:
<tbody v-for="row in rows" :key="index">
<tr>
<td>
<select @change="selected" v-model="product_id" class="form-control" name="product_id" id="product_id">
<option value="">Select Product</option>
<option v-for="item in items" :value="item.id" v-text="item.product_name"></option>
</select>
</td>
<td>
<textarea type="text" v-model="product.product_details" name="product_details" id="product_details" class="form-control" rows="1" placeholder="Product Details">
</textarea>
</td>
<td>
<input v-model.number="product.product_sellPrice" type="number" step="any" class="form-control" name="rate" id="rate" placeholder="Rate">
</td>
<td>
<input v-model.number="product.product_tax" type="number" step="any" class="form-control" name="tax" id="tax" placeholder="Tax">
</td>
<td>
<input v-model="quantity" type="number" class="form-control" name="quantity" id="quantity" placeholder="Quantity">
</td>
<td>
<input :value="total" type="number" step="any" class="form-control" name="total" id="total" placeholder="Total Price">
</td>
<td>
<button class="btn btn-secondary" v-on:click="addrow" >
<i class="fa fa-plus" aria-hidden="true"></i>
</button>
<button v-show="length > 1" class="btn btn-secondary" @click.prevent="removerow(index)">
<i class="fa fa-minus" aria-hidden="true"></i>
</button>
</td>
</tr>
</tbody>
<script>
export default{
props: ['products'],
data() {
return {
rows: [{
}],
items: this.products,
product: '',
product_id: '',
quantity: '',
index: '',
total_price: '',
}
},
methods: {
addrow: function (event) {
event.preventDefault();
this.rows.push({
});
},
removerow: function (index) {
this.rows.splice(index, 1);
},
selected(e){
var id = this.product_id;
console.log(id);
axios.get('/estimate/product/' + id)
.then((response)=>{
this.product = '';
this.product = response.data;
})
.catch((error) => {
console.log(error);
});
},
}
}
</script>
我在哪里做错了?我该如何解决? 感谢。
答案 0 :(得分:1)
key
应该是每行的唯一标识符。您在index
对象中定义了data
,并将其用作所有行作为键,这会导致问题。
此外,建议不要将行索引用作键,因为在添加/删除行时它会更改。
因此,您需要为每个行项添加一些标识符并将其用作键,以下是如何执行此操作的简单示例:
<div id="vue-instance">
<ul>
<li v-for="(index,item) in inventory" :key="item.name">
{{ item.name }} - ${{ item.price }}
<button @click="add">Add</button>
<button @click="remove(index)">Remove</button>
</li>
</ul>
</div>
var vm = new Vue({
el: '#vue-instance',
data: {
counter: 1,
inventory: [{
name: 'MacBook Air',
price: 1000
}, {
name: 'MacBook Pro',
price: 1800
}, {
name: 'Lenovo W530',
price: 1400
}, {
name: 'Acer Aspire One',
price: 300
}]
},
methods: {
add: function() {
this.inventory.push({
name: 'item' + this.counter++,
price: this.counter * 1000
})
},
remove: function(index) {
this.inventory.splice(index, 1);
}
}
});