<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>购物车</title>
</head>
<body>
<div id="app">
<h1>{{msg}}</h1>
编号:<input type="text" v-model="no"> 名称:
<input type="text" v-model="na"> 价格:
<input type="text" v-model="pr"> 数量:
<input type="text" v-model="num">
<button @click="addCart">添加到购物车</button>
<table border="1">
<tr>
<th>编号</th>
<th>名称</th>
<th>价格</th>
<th>购买数量</th>
<th>小计</th>
</tr>
<tr v-for="(item,index) in lists" :key="index">
<th>{{lists[index].id}}</th>
<th>{{lists[index].name}}</th>
<th>{{lists[index].price}}</th>
<th><input type="button" value="+" @click="add(index)">{{lists[index].number}}<input type="button" value="-" @click="reduce(index)"></th>
<th>{{(lists[index].price*lists[index].number).toFixed(2)}}</th>
<!-- 保留两位小数 -->
</tr>
</table>
<h1>总价格 :{{ totalPrice().toFixed(2) }}</h1>
</div>
</body>
</html>
<script src="js/vue.js"></script>
<script>
var app = new Vue({
el: "#app",
data: {
msg: "购物车案例",
lists: [{
id: 1,
name: "iphone8",
price: 19.9,
number: 1
}, {
id: 2,
name: "meta40 pro",
price: 15,
number: 1
}, ],
sum: 0,
items: {},
no: '',
na: '',
pr: '',
num: ''
},
methods: {
add(index) {
this.lists[index].number++;
},
reduce(index) {
if (this.lists[index].number > 0) {
this.lists[index].number--;
} else {
this.lists[index].number == 0;
}
},
totalPrice() {
//计算总价格
var totalPrice = 0;
for (var i = 0; i < this.lists.length; i++) {
var price = this.lists[i].number * this.lists[i].price;
totalPrice += price;
}
return totalPrice;
},
addCart() {
this.items = {
id: this.no,
name: this.na,
price: this.pr,
number: this.num
}
this.lists.push(this.items)
}
}
})
</script>