代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>购车商品总价计算</title>
</head>
<body>
<div id="app">
<h1>购物车</h1>
<input type="checkbox" v-model="checkedAll" />全选
<ul>
<li v-for="product in products" :key="product.id">
<input type="checkbox" v-model="product.checked" />{
{product.name}}
<span style="color: deeppink;">{
{product.price}}</span>
<button @click="subtract(product)">-</button>
<!-- product.amount-- -->
<span>{
{product.amount}}</span>
<button @click="product.amount++">+</button>
</li>
</ul>
<p>总价:{
{sumPrice}}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var app = new Vue({
el: "#app",
data: {
products: [
{
id: 1,
amount: 1,
name: "Mac mini 2020",
price: 8000,
checked: false,
},
{
id: 2,
amount: 1,
name: "red Mi Pro",
price: "5000",
checked: false,
},
{
id: 3,
name: "手办",
price: 100,
amount: 1,
checked: false,
},
],
},
methods: {
subtract(product){ // 接收一个参数
console.log(product)
product.amount--
if(product.amount<1){
product.amount = 0
}
}
},
computed: {
sumPrice() {
// reduce
// 对数组中的数据做聚合操作
// 接收参数
// 参数一 回调函数
// 参数一 表示上一次的值(上一次的计算结果,第一次时候传递的是初始值)
// 参数二 当前项
// 参数二 初始值
// return this.products.reduce(function (pre, cur) {
// console.group("reduce执行了");
// console.log(pre);
// console.log(cur);
// console.groupEnd();
// return pre + cur.price * cur.amount;
// }, 0);
return this.products
.filter((item) => item.checked)
.reduce((pre, cur) => pre + cur.price * cur.amount, 0);
},
checkedAll: {
get() {
return (
// 判断选中的长度是否等于总长度
this.products.filter((item) => item.checked).length ===
this.products.length
);
},
set(val) {
this.products.forEach((item) => (item.checked = val));
},
},
},
});
</script>
</body>
</html>