<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>购物车</title>
<style type="text/css">
.active {
background-color: lightsalmon;
}
</style>
</head>
<body>
<div id="app">
<h2>购物车</h2>
<div class="main">
<table border="1" width="60%" style="text-align: center;">
<thead>
<tr style="background-color: lightgray">
<th>选中</th>
<th>名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</tr>
</thead>
<!-- 有数据,才渲染 -->
<tbody v-if="fruitList.length > 0">
<tr v-for="(item,index) in fruitList" :key="item.id" :class="{ active: item.isChecked}">
<td>
<input type="checkbox" v-model="item.isChecked">
</td>
<td>{{ item.title }}</td>
<td>{{ item.price }}</td>
<td>
<button class="decrease" @click="sub(item.id)" :disabled="item.num <= 1">-</button>
<span>{{ item.num }}</span>
<button class="increase" @click="add(item.id)">+</button>
</td>
<td>{{ item.num * item.price }}</td>
<td><button @click="del(item.id)">删除</button></td>
</tr>
</tbody>
<!-- 无数据,显示空 -->
<tbody v-else>
<tr>
<td colspan="6">空空如也</td>
</tr>
</tbody>
<tfoot>
<tr v-if="fruitList.length > 0">
<td>
<input type="checkbox" v-model="isAll">全选
</td>
<td colspan="3"> </td>
<td colspan="2">
<span>总价:¥<strong>{{ totalPrice }}</strong></span>
<button>结算({{ totalCount }})</button>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
<script src="../js/vue.js"></script>
<script>
const defaultArr = [
{
id:1,
title:'苹果',
isChecked:true,
num:2,
price:6
},
{
id:2,
title:'香蕉',
isChecked:false,
num:7,
price:20
},
{
id:3,
title:'葡萄',
isChecked:true,
num:3,
price:11
},
{
id:4,
title:'桃子',
isChecked:false,
num:8,
price:16
},{
id:5,
title:'香梨',
isChecked:false,
num:12,
price:9
},{
id:6,
title:'火龙果',
isChecked:true,
num:12,
price:26
}
];
const app = new Vue({
el:'#app',
data:{
fruitList: JSON.parse(localStorage.getItem('list')) || defaultArr,
},
computed:{
//全选与反选
isAll:{
get(){
//通过every,判断每一项是否都选择了
return this.fruitList.every( item => item.isChecked === true)
},
set(value){
//撤销全选,同步每一项
this.fruitList.forEach( item => item.isChecked = value)
}
},
//统计选中的总数
totalCount(){
return this.fruitList.reduce( (sum,item) => {
if(item.isChecked){
return sum + item.num
} else {
return sum
}
},0);
},
//统计选中的总价
totalPrice(){
return this.fruitList.reduce( (sum,item) => {
if(item.isChecked){
return sum+ item.num * item.price
} else{
return sum
}
},0)
}
},
methods:{
//删除
del(id){
//filter过滤,把要删除的过滤掉
this.fruitList = this.fruitList.filter( item => item.id !== id);
},
add(id){
//根据id查询对应
const fruit = this.fruitList.find( item => item.id === id);
//操作数量
fruit.num++
},
sub(id){
const fruit = this.fruitList.find( item => item.id === id);
fruit.num--
}
},
watch:{
fruitList :{
deep:true,
handler(newValue){
//需要将变化的数据保存本地
localStorage.setItem('list',JSON.stringify(newValue));
}
}
}
})
</script>
</body>
</html>
vue 综合案例-水果购物车
最新推荐文章于 2023-12-16 20:18:22 发布