要求:
动态添加菜品个数
实现菜品数量的添加和减少
菜品数量变化后计算出总价格
当数量减为0时再次点击减少按钮就移除菜品
完整代码:
<!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>
<script src='https://cdn.jsdelivr.net/npm/vue/dist/vue.js'></script>
</head>
<body>
<style>
#app{
width: 500px;
margin: 0 auto;
background-color: antiquewhite;
}
.box{
width: 100%;
height: 80px;
display: flex;
justify-content: space-between;
margin-bottom: 20px;
/* background-color: aquamarine; */
}
img{
width: 70px;
height: 70px;
}
.order{
width: 200px;
height: 100px;
display: flex;
flex-direction:column;
margin-left: 30px;
}
.btn{
width: 100px;
height: 20px;
display: flex;
justify-content: flex-start;
}
.total{
width: 100%;
text-align:center;
}
.title{
width: 100%;
text-align:center;
}
</style>
<div id='app'>
<div style="width: 100%;text-align: center;font-size: 40px;">菜单</div>
<!-- 动态添加菜品 -->
<div v-for="(el,index) in arr" class="box" :key="el.id" >
<!-- 菜品图片 -->
<img :src="el.imgurl" alt="">
<div class="order">
<!-- 菜品名称和价格 -->
<span>{{el.name}}</span>
<p>单价:{{el.price}}</p>
</div>
<div class="btn">
<!-- 添加和减少按钮 -->
<button @click="reduce(index)">-</button>
<span>{{el.count}}</span>
<button @click="add(index)">+</button>
</div>
</div>
<!-- 总价 -->
<div class="total" :style="{display:m}">总价:{{total}}元</div>
<div class="title":style={display:n}>还没点哟!</div>
</div>
<script>
new Vue({
el:'#app',
data: {
arr:[{
id:123,
name:"重庆鸡公煲",
imgurl:"./img/3.jpg",
price:12,
count:0,
},{
id:124,
name:"砂锅米线",
imgurl:"./img/4.jpg",
price:5,
count:0,
},{
id:125,
name:"凉拌猪耳朵",
imgurl:"./img/5.jpg",
price:10,
count:0
},{
id:126,
name:"麻辣干锅",
imgurl:"./img/9.jpg",
price:29,
count:0,
},{
id:127,
name:"辣子鸡",
imgurl:"./img/10.jpg",
price:34,
count:0,
},{
id:128,
name:"橙子",
imgurl:"./img/12.jpg",
price:20,
count:0,
}
],
m:"block",
n:"none"
},
methods: {
// 减少按钮
reduce(index){
// 点击按钮后减少count数量
this.arr[index].count--
// 当count数量减少为-1时移除菜品
if(this.arr[index].count==-1){
console.log(22222,this.arr.length,index)
this.arr.splice(index,1)
// 当删除完所有菜品时刷新页面,结束退出函数
if(this.arr.length==0){
this.m="none"
this.n="block"
this.arr=[]
return
}
}
// 刷新页面
Vue.set(this.arr,0,this.arr[0])
},
// 增加按钮
add(index){
// 增加菜品数量
this.arr[index].count++
// 刷新页面
Vue.set(this.arr,0,this.arr[0])
}
},
computed: {
// 计算总价
total(){
var all=0
this.arr.forEach(el => {
all+=el.count*el.price
});
return all
}
}
})
</script>
</body>
</html>
遇到的问题:
- 键点击任意一个按钮增加或者减少菜品数量时其他菜品数量也要变化:没有每个盒子绑定key值,将每个菜品都带上独一无二的id使用for循环遍历数组生成盒子时给每个盒子都绑定key值。
- 设置减少按钮时,移除到最后一个盒子时移除不掉:因为我刷新页面的语句是将数组的第一个的值设置成为第一个本身的值,当我们删除最后一个值时,数组里面就空了,这时再执行书信语句就会报错,所以我们就需要添加一个判断,当数组长度为0 时就将arr设置为一个空数组来书信页面,使用return跳出函数完成页面最后一个菜品的删除