<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#app{
width: 60%;
margin: 10px auto;
}
.inp{
margin-bottom: 30px;
}
.inp input{
width: 30%;
height: 35px;
line-height: 35px;
padding-left: 4px;
}
td{
text-align: center;
}
td span{
cursor: pointer;
}
.total td{
text-align: right;
padding-right: 20px;
}
.selAll{
width: 35px;
height: 35px;
border-radius: 50%;
background: #eee;
cursor: pointer;
text-align: center;
line-height: 35px;
display: inline-block;
margin: 0 3px;
}
</style>
</head>
<body>
<div id="app">
<div class="inp">
<input type="text" v-model.trim="goodsName" placeholder="请输入商品名称" />
<input type="number" v-model.number="goodsPrice" placeholder="请输入价格" />
<button @click="add">添加</button>
</div>
<table border="1" width="100%" cellspacing="0" cellpadding="0">
<tr>
<th><span @click="all" class="selAll">全选</span> 名称</th>
<th>单价(元)</th>
<th>数量</th>
<th>总价(元)</th>
<th>操作</th>
</tr>
<tr v-for="(val,index) in arr">
<td><input v-model="val.isCheck" @change="sel" type="checkbox" /> {{val.name}}</td>
<td>{{val.price}}</td>
<td><span @click="reduce(index)">-</span> {{val.count}} <span @click="plus(index)">+</span></td>
<td>{{(val.price*val.count).toFixed(2)}}</td>
<td @click="del(index)">删除</td>
</tr>
<tr class="total">
<td colspan="5">总价格:{{allPrice}}</td>
<!--<td colspan="5">总价格:{{total.toFixed(2)}}</td>-->
</tr>
</table>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript">
//数据驱动视图
var vm = new Vue({
el:"#app",
data:{
goodsName:"白菜",
goodsPrice:16,
arr:[],
obj:{},
total:0
},
methods:{
add(){//增加条目
this.obj = {
isCheck:false,
name:this.goodsName,
price:this.goodsPrice,
count:1,
totalPrice:1*parseInt(this.goodsPrice)
}
//this.arr.push(this.obj);
vm.$set(vm.arr,vm.arr.length,vm.obj);
},
reduce(index){//减少商品数量
if(this.arr[index].count>0){
this.arr[index].count--;
this.sel();
}
},
plus(index){//增加商品数量
this.arr[index].count++;
this.sel();
},
del(index){//删除条目
this.arr.splice(index,1);
this.sel();
},
sel(){//计算选择到的商品的总价格
this.total = 0;
for(var i=0;i<this.arr.length;i++){
if(this.arr[i].isCheck){
var {count,price} = this.arr[i];
this.total+=count*price;
}
}
},
all(){//全选
var res = this.arr.every(val=>{
return val.isCheck;
})
this.arr.forEach(val=>{
if(res){
val.isCheck = false;
}else{
val.isCheck = true;
}
})
}
},
computed:{ //计算属性
allPrice(){//计算选中商品的总价格
var total = 0;
for(let i=0;i<this.arr.length;i++){
if(this.arr[i].isCheck){
let {count,price} = this.arr[i];
total += count*price;
}
}
return total.toFixed(2);
}
}
})
</script>
</body>
</html>
网友评论