You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
78 lines
1.3 KiB
78 lines
1.3 KiB
<template> |
|
<div class="carts"> |
|
<h1>购物车</h1> |
|
<hr /> |
|
<label><input type="checkbox" v-model="checkAll" />全选</label> |
|
<hr /> |
|
<ul> |
|
<li v-for="item in carts" :key="item.id"> |
|
<label> |
|
<input type="checkbox" v-model="item.chk" /> |
|
{{ item.name }} |
|
</label> |
|
<p> |
|
数量: |
|
<button @click="item.amount > 1 ? item.amount-- : null"> |
|
- |
|
</button> |
|
{{ item.amount }} |
|
<button @click="item.amount++">+</button> |
|
</p> |
|
<p>价格:{{ item.price }}</p> |
|
</li> |
|
</ul> |
|
<p>总价值:{{ sumPrice }}</p> |
|
</div> |
|
</template> |
|
<script setup> |
|
import { ref, computed } from "vue"; |
|
const carts = ref([ |
|
{ |
|
id: 1, |
|
name: "huawei", |
|
chk: true, |
|
amount: 2, |
|
price: 5000, |
|
}, |
|
{ |
|
id: 2, |
|
name: "xiaomi", |
|
chk: true, |
|
amount: 5, |
|
price: 3000, |
|
}, |
|
{ |
|
id: 3, |
|
name: "oppo", |
|
chk: false, |
|
amount: 3, |
|
price: 4000, |
|
}, |
|
]); |
|
|
|
const checkAll = computed({ |
|
// 主动设置值=v |
|
set(v) { |
|
carts.value.forEach((item) => (item.chk = v)); |
|
}, |
|
// 被动改变值 |
|
get() { |
|
return carts.value.every((item) => item.chk); |
|
}, |
|
}); |
|
|
|
const sumPrice = computed( |
|
() => |
|
carts.value |
|
.filter((item) => item.chk) // 获取选中的商品 |
|
.reduce((pre, cur) => pre + cur.amount * cur.price, 0) // 求和 |
|
); |
|
</script> |
|
|
|
<style scoped> |
|
li { |
|
list-style: none; |
|
padding: 8px; |
|
border-bottom: 1px solid black; |
|
} |
|
</style>
|
|
|