我正在学习Vue。
现在,我尝试添加价格数据,最后,它计算总价格:
这是HTML
<div id="app">
<form @submit.prevent="addItem">
<table border="1" cellpadding="10" width="300">
<tr>
<td colspan="2"><strong>Add New Item</strong></td>
</tr>
<tr>
<td>
<input type="text" name="" v-model="newItem" placeholder="Item Name">
</td>
<td>
<input type="number" name="" v-model="newItemPrice" placeholder="Item Price">
</td>
</tr>
</table>
</form>
<br>
<table border="1" cellpadding="10" width="400">
<tr>
<th>Item Name</th>
<th>Item Price</th>
</tr>
<tr v-for="(item, index) in items" :key="index">
<td>{{ item.name }}</td>
<td><input type="number" name="" v-model="item.price"></td>
<td><button @click="removeItem(index)">X</button></td>
</tr>
<tr>
<td>Total</td>
<td><strong>{{ total }}</strong></td>
</tr>
</table>
</div>
这是Vue实例:
new Vue({
el : '#app',
data : {
items: [
{ name: 'Rice', price : 12.60 },
{ name: 'Oil', price : 22.00 },
{ name: 'Mango', price : 32.50 },
{ name: 'Orange', price : 42.00 },
],
newItem : '',
newItemPrice : '',
},
computed: {
total() {
var total = 0;
this.items.forEach( item => {
total += parseFloat( item.price );
})
return total;
}
},
methods: {
addItem() {
this.items.push({
name: this.newItem,
price: 0
});
},
removeItem( index ) {
this.items.splice( index, 1 )
}
}
});
You can see it's by default showing item name and price. I want to add new item using the v-model called newItem
But It's not adding the new item to the table
但
如果删除项目价格列,则表示以下行:
<td>
<input type="number" name="" v-model="newItemPrice" placeholder="Item Price">
</td>
然后完美地添加新项目:(
你能告诉我这里怎么了吗?
This happens because when you have only one item in the form, then it auto-triggers the form submit on
enter
keypress, as there is no need to validate other elements in the form. But in case of multiple elements, theenter
keypress is not triggered and form is never submitted and thus you get this behaviour.To resolve this you can simply use
@keyup.enter.prevent="addItem"
to listen to theenter
keypress on each input and call theaddItem()
function like:查看小提琴的两个问题:
修复它们两个之后,在此小提琴中效果很好。
You should put a new line in your form, my suggestion is to put just above the close form tag
</form>
:Another fix to do is in your methods
addItem()
Where it is the number
0
you should provide thethis.newItemPrice
to it work properly.