<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app" align="center">
编号:<input type="text" v-model="commodity.id"><br>
名称:<input type="text" v-model="commodity.name"><br>
价格:<input type="text" v-model="commodity.price"><br>
购买数量:<input type="text" v-model="commodity.count"><br>
<button v-on:click="add">添加到购物车</button>
<table border="1">
<tr>
<th>编号</th>
<th>名称</th>
<th>价格</th>
<th>购买数量</th>
<th>小计</th>
</tr>
<tr v-for="(item,index) in items">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td><button v-on:click="decreament(index)">-</button>{{item.count}}<button v-on:click="increament(index)">+</button></td>
<td>{{item.count * item.price}}</td>
</tr>
</table>
<h3>总价格: {{totalPrice()}} 元</h3>
</div>
</body>
</html>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
var app = new Vue({
el: "#app",
data: {
items:[
{id:1, name:"iphone13", price:"6", count:5},
{id:2, name:"mate 40 pro", price:"10", count:3},
],
commodity:{}
},
methods:{
decreament(index){
if(this.items[index].count>0){
this.items[index].count--;
}
},
increament(index){
this.items[index].count++;
},
totalPrice(){
var totalPrice = 0;
for (var i = 0; i < this.items.length; i++) {
totalPrice += this.items[i].count * this.items[i].price;
}
return totalPrice;
},
add(){
if(!this.commodity.id){
alert("请输入编号!!!")
return false;
}
if(!this.commodity.name){
alert("请输入名称!!!")
return false;
}
if(!this.commodity.price){
alert("请输入价格!!!")
return false;
}
if(!this.commodity.count){
alert("请输入购买数量!!!")
return false;
}
this.items.push(this.commodity)
}
}
});
</script>