要求:
动态添加菜品个数
实现菜品数量的添加和减少
菜品数量变化后计算出总价格
当数量减为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>
遇到的问题: