<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="js/vue.js"></script>
<link rel="stylesheet" href="css/bootstrap.css" />
<style>
button {
border: none;
outline: none;
}
</style>
</head>
<body>
<div id="wrap">
<div class="container">
<table class="table table-bordered table-hover text-center">
<tr>
<td>商品名称</td>
<td>商品价格</td>
<td>商品数量</td>
<td>商品总额</td>
<td>操作</td>
</tr>
<tr v-for="(item,index) in shoppList">
<td>{{item.shoppName}}</td>
<td>{{item.shoppPrice}}</td>
<td>
<button type="button" class="btn-danger" @click="minus(index)">-</button>
<input type="text" v-model="item.shoppCount" />
<button type="button" class="btn-success" @click="add(index)">+</button>
</td>
<td>
{{item.shoppPrice*item.shoppCount}}
</td>
<td>
<button class="btn btn-danger" @click="del(index)">删除</button>
</td>
</tr>
</table>
<p class="text-right">金额总计:{{sum}}</p>
<p class="text-right">商品数量总计:{{count}}</p>
<hr />
<form>
<h3>添加商品</h3>
<div class="form-group">
<input type="text" placeholder="请输入商品名称" class="form-control" v-model="shoppName" />
</div>
<div class="form-group">
<input type="text" placeholder="请输入商品价格" class="form-control" v-model="price" />
</div>
<div class="form-group">
<button class="btn btn-warning" type="button" @click="addInfo()">添加</button>
</div>
</form>
</div>
</div>
<script>
var vm = new Vue({
el: "#wrap",
data: {
shoppList: [{
id: 1,
shoppName: "苹果手机",
shoppPrice: 2800,
shoppCount: 0
},
{
id: 2,
shoppName: "华为手机",
shoppPrice: 2400,
shoppCount: 0
},
{
id: 3,
shoppName: "小米手机",
shoppPrice: 2200,
shoppCount: 0
},
],
shoppName: "",
price: ""
},
methods: {
add: function(index) {
this.shoppList[index].shoppCount++
},
minus: function(index) {
if(this.shoppList[index].shoppCount <= 0) {
this.shoppList[index].shoppCount = 0
} else {
this.shoppList[index].shoppCount--
}
},
addInfo: function() {
if(this.shoppName.length==0) {
alert("商品名称不能为空")
} else if(this.price.length==0){
alert("商品价格不能为空")
} else {
var obj = {
id: this.shoppList.length + 1,
shoppName: this.shoppName,
shoppPrice: this.price,
shoppCount: 0
}
this.shoppList.push(obj)
this.shoppName = ""
this.price = ""
}
},
del:function(index){
this.shoppList.splice(index,1)
}
},
//计算属性,数据多次调用,不会刷新页面
computed: {
//有返回值,是个属性,调用-->不用括号
sum() {
var total = 0
for(var i = 0; i < this.shoppList.length; i++) {
total += parseFloat(this.shoppList[i].shoppPrice) * parseFloat(this.shoppList[i].shoppCount)
}
return total
},
count() {
var total = 0
for(var i = 0; i < this.shoppList.length; i++) {
total += parseInt(this.shoppList[i].shoppCount)
}
return total
}
}
})
</script>
</body>
</html>
显示: