Vue写一个购物车计算器
CSS部分:
*{
margin: 0;
padding: 0;
}
.box{
box-sizing: border-box;
margin: 0 auto;
width: 480px;
height: 590px;
background-image: url(./images/bg.png);
}
/* 按钮 */
.minus,
.add{
display: inline-block;
width: 52px;
height: 44px;
cursor: pointer;
vertical-align: middle;
background-image: url(./images/sub.png);
}
.add{
background-image: url(./images/add.png);
}
.pronum,
.info{
box-sizing: border-box;
padding: 0 5px;
min-width: 40px;
height: 35px;
line-height: 35px;
background: #fff;
border-radius: 3px;
text-align: center;
vertical-align: middle;
}
.pronum{
display: inline-block;
}
.top{
padding: 50px 20px 0;
height: 387px;
}
.hang{
margin-bottom: 20px;
display: flex;
justify-content: space-between;
align-items: flex-start;
}
.hang .info{
box-sizing: border-box;
padding: 0 10px;
width: 260px;
color: white;
font-size: 14px;
text-align: left;
line-height: 35px;
background: #171818;
}
.bottom{
padding-top: 20px;
color:#878787;
padding-left: 50px;
line-height: 40px;
}
HTML部分:
在这里插入<!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>Vue版计算器</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="box" id="app">
<div class="top">
<div class="hang" v-for="item in list" :key="item.id">
<i class="minus" @click="handle(item.id,'minus')"></i>
<span class="pronum">{{item.count}}</span>
<i class="add" @click="handle(item.id,'plus')"></i>
<span class="info">
单价:{{item.price}}元
小计:{{(item.count*item.price).toFixed(2)}}元
</span>
</div>
</div>
<div class="bottom">
商品合计:<span class="pronum">{{counts}}</span> 件
<br>
共花费了:<span class="pronum">{{prices}}</span> 元
<br>
最贵的商品单价:<span class="pronum">{{maxprice}}</span> 元
</div>
</div>
<!--IMPORT JS-->
<script src="/node_modules/vue/dist/vue.js"></script>
<script>
let list = [{
id: 1,
count: 0,
price: 12.5
}, {
id: 2,
count: 0,
price: 10.5
}, {
id: 3,
count: 0,
price: 8.5
}, {
id: 4,
count: 0,
price: 8
}, {
id: 5,
count: 0,
price: 14.5
}];
let vm=new Vue({
el:"#app",
data:{
list
},
computed:{
counts(){
return this.list.reduce((result,item)=>result+item.count,0)
},
prices(){
return this.list.reduce((result,item)=>result+(item.count*item.price),0).toFixed(2);
},
maxprice(){
let arr=[0];
this.list.forEach(item=>{
if(item.count>0){
arr.push(item.price);
}
});
return Math.max(...arr)
}
},
methods:{
handle(id,type){
let item=this.list.find(item=>+item.id===+id);
if(!item)return;
if(type==="plus"){
item.count++;
return;
}
item.count--;
if(item.count<0)item.count=0
}
}
})
</script>
</body>
</html>代码片
背景图片: