<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./js/vue.js"></script>
<style>
th {
width: 150px;
}
</style>
</head>
<body>
<div id="app">
<h1>购物车清单</h1>
<table border="1">
<thead>
<tr>
<th>
全选 <input type="checkbox" v-model="checkAll">
</th>
<th>商品</th>
<th>数量</th>
<th>单价</th>
<th>金额</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in list">
<td>
<input type="checkbox" v-model="item.isChecked">
</td>
<td>{{ item.title }}</td>
<td>
<button @click="decrement(index)">-</button>
<span>{{ item.count }}</span>
<button @click="increment(index)">+</button>
</td>
<td>{{ item.price }}</td>
<td>{{ item.count * item.price }}</td>
</tr>
</tbody>
</table>
<button @click="del">删除所选商品</button>
<h2>共选中{{ n }}件商品</h2>
<h2>总金额:{{totalPrice}}</h2>
</div>
<script>
let vm = new Vue({
el: '#app',
data: {
checkOne: true,
list: [
{
title: "香蕉",
count: 1,
price: 1.5,
isChecked: false
},
{
title: "榴莲",
count: 2,
price: 100,
isChecked: false
},
{
title: "苹果",
count: 1,
price: 2.5,
isChecked: false
}
]
},
methods: {
del() {
var arr = this.list.filter(item => {
return !item.isChecked
})
this.list = arr;
},
decrement(i) {
if (this.list[i].count == 1) return
this.list[i].count--
},
// 加
increment(i) {
this.list[i].count++
}
},
computed: {
n() {
// 根据list数组内有几个项目的isChecked为true
var arr = this.list.filter(item => {
return item.isChecked == true
})
return arr.length;
},
totalPrice() {
// 根据list数组有几个isChecked为true,计算金额总和
var arr = this.list.filter(item => {
return item.isChecked == true
})
var sum = 0;
arr.forEach(item => {
sum += item.count * item.price
})
return sum
},
checkAll: {
// 触发时机:checkAll所依赖的list发生改变就会重新计算
get() {
// 被动,全选是否打钩,取决于所有商品的checkbox是否打钩
// true => list里所有商品的isChecked都为true
return this.list.every(item => {
return item.isChecked == true
})
},
set(newVal) {
// 更改所有商品的isChecked
// 如果全选打钩了,那就让所有商品的isChecked为true
this.list.forEach(item => {
item.isChecked = newVal
})
}
}
}
});
</script>
</body>
</html>
vue-购物车
最新推荐文章于 2022-09-18 21:37:18 发布