vue商品价格数量总价同步变化案例
效果动图
代码展示
<!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>Document</title>
</head>
<body>
<div id="app">
<table>
<tbody>
<tr>
<td>
<input type="checkbox" :checked="aa.checked" @click="acb">
</td>
<td>{{aa.name}}</td>
<td>
<span>¥</span>
<span>{{aa.price}}</span>
</td>
<td>
<button @click="ajian">-</button>
<span>{{aa.num}}</span>
<button @click="ajia">+</button>
</td>
<td>
<span>¥</span>
<span>{{aa.aprice}}</span>
</td>
</tr>
<tr>
<td>
<input type="checkbox" :checked="bb.checked" @click="bcb">
</td>
<td>{{bb.name}}</td>
<td>
<span>¥</span>
<span>{{bb.price}}</span>
</td>
<td>
<button @click="bjian">-</button>
<span>{{bb.num}}</span>
<button @click="bjia">+</button>
</td>
<td>
<span>¥</span>
<span>{{bb.bprice}}</span>
</td>
</tr>
<tr>
<td>共{{znum}}件</td>
<td>总价:¥{{zprice}}</td>
</tr>
</tbody>
</table>
</div>
<script src="https://cdn.staticfile.org/vue/2.6.9/vue.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
aa: {
name: 'iphone6',
price: 600,
num: 1,
aprice: 0,
checked: false
},
bb: {
name: 'iphone7',
price: 800,
num: 1,
bprice: 0,
checked: false
},
zprice: 0,
znum: 0
},
created() {
this.aa.aprice = this.aa.price * this.aa.num
this.bb.bprice = this.bb.price * this.bb.num
this.znp()
},
methods: {
acb() {
if (this.aa.checked == true) {
this.aa.checked = false
} else if (this.aa.checked == false) {
this.aa.checked = true
}
this.znp()
},
bcb() {
if (this.bb.checked == true) {
this.bb.checked = false
} else if (this.bb.checked == false) {
this.bb.checked = true
}
this.znp()
},
ajian() {
if (this.aa.num > 0) {
this.aa.num--
}
this.aa.aprice = this.aa.price * this.aa.num
this.znp()
},
ajia() {
this.aa.num++
this.aa.aprice = this.aa.price * this.aa.num
this.znp()
},
bjian() {
if (this.bb.num > 0) {
this.bb.num--
}
this.bb.bprice = this.bb.price * this.bb.num
this.znp()
},
bjia() {
this.bb.num++
this.bb.bprice = this.bb.price * this.bb.num
this.znp()
},
znp() {
if (this.aa.checked != false && this.bb.checked != false) {
this.znum = this.aa.num + this.bb.num
this.zprice = this.aa.aprice + this.bb.bprice
} else if (this.aa.checked != false && this.bb.checked == false) {
this.znum = this.aa.num
this.zprice = this.aa.aprice
} else if (this.aa.checked == false && this.bb.checked != false) {
this.znum = this.bb.num
this.zprice = this.bb.bprice
} else {
this.znum = 0
this.zprice = 0
}
}
}
});
</script>
</body>
</html>