. 全选
. 部分选择
. 结算
. 待选商品 lists:数组;本地数据或使用 fetch 或 axios加载远程数据
. 选中商品 selectedLists;数组
. 是否全选 isAll,布尔;默认是真,全选
. 商品数量总数 count;数值
. 商品价格总数 totalPrice;数值
. 商品折扣价格总数 discountPrice;数值
import { useCartStore } from '@/stores/cart'; const cartStore = useCartStore(); const lists = ref([]) const selectedLists = ref([]) const isAll = ref(false) const totalPrice = ref(0) const discountPrice = ref(0) const count = ref(0) onMounted(() => { lists.value = cartStore.lists; selectedLists.value = [...lists.value] })
. 列表渲染多个商品项
. 每个商品项的选择和 selectedLists 使用双向绑定
<div v-for="(cart, ind) in lists"> <input type="checkbox" name="cart" v-model="selectedLists" :value="cart"> // .商品信息,可以封装为组件 </div>
. 侦听 selectedLists:如果选中列表长度和商品列表长度相等,则全选为真;否则全选为假
. 其它业务
watch(selectedLists, (newVal) => { isAll.value = newVal.length == lists.value.length // 总价结算 totalPrice // 数量结算 count // 折扣 discountPrice }, { deep: true, immediate: true })
. 单击商品项的增加和减少按钮相应的调整其数量;并根据库存进行越界检测
. 这里使用内联事件方式;也可以使用函数方式
<button class="btn" @click="cart.quantity--" :disabled="cart.quantity <= 1">-</button>
<button class="btn" @click="cart.quantity++" :disabled="cart.quantity >= cart.stock">+</button>
. 双向绑定 isAll
. 使用改变事件,判断是全选还是全不选
<input type="checkbox" name="all" v-model="isAll" @change="selectAllChange"/>all
const selectAllChange = () => { if (isAll.value) { selectedLists.value = [...lists.value] } else { selectedLists.value = [] } }
. 确保侦听为深度侦听和立即侦听:便于页面渲染完毕时立即更新数据;或使用自动侦听 watchEffect
totalPrice.value = selectedLists.value.reduce((total, item) => total + item.quantity * item.price * (1 - item.discount), 0).toFixed(2)
count.value = selectedLists.value.reduce((total, item) => total + item.quantity, 0)
discountPrice.value = selectedLists.value.reduce((total, item) => total + item.quantity * item.price * item.discount, 0).toFixed(2)
. 按数量排序
const isAscending = ref(true) const sortQuantity = () => { isAscending.value = !isAscending.value return lists.value.sort((a, b) => isAscending.value ? a.price - b.price : b.price - a.price) }
. 按字母排序
const islocaleCompare = ref(true) const sortTitle = () => { islocaleCompare.value = !islocaleCompare.value return lists.value.sort((a, b) => islocaleCompare.value ? a.title.localeCompare(b.title) : b.title.localeCompare(a.title)) }