此购物篮卡片组件可用于构建电子商务网站或移动应用程序中的购物篮页面,方便用户查看和管理购物车中的商品。
1. 初始化购物车数据
const cart = ref([
{
id: 1,
name: "Peach",
image: "https://source.unsplash.com/random/100x100",
price: 3.15,
quantity: 2,
},
// ... 其他商品数据
]);
此代码使用 Vue 的 ref
响应式对象来管理购物车数据,并定义了每个商品的属性,包括 ID、名称、图片、价格和数量。
2. 渲染购物车列表
<van-cell
v-for="item in cart"
:key="item.id"
title=""
label=""
class="border-b border-gray-200"
>
<!-- 商品信息 -->
<template #title>
<div class="flex items-center">
<van-image class="w-10 h-10 rounded-full mr-2" :src="item.image" />
<span class="text-gray-500 text-base font-medium">{{ item.name }}</span>
</div>
</template>
<!-- 商品数量和价格 -->
<template #label>
<div class="flex items-center justify-between">
<div class="flex items-center">
<van-icon name="minus" class="text-gray-500 mr-2" />
<span class="text-gray-500 text-base font-medium">
{{ item.quantity }}
</span>
<van-icon name="plus" class="text-gray-500 ml-2" />
</div>
<span class="text-red-500 text-base font-medium">
${{ item.price }}
</span>
</div>
</template>
</van-cell>
此代码使用 Vue 的 v-for
循环遍历购物车中的商品,并使用 van-cell
组件来显示每个商品的信息,包括商品图片、名称、数量和价格。
3. 调整商品数量
<van-icon name="minus" class="text-gray-500 mr-2" />
<span class="text-gray-500 text-base font-medium">
{{ item.quantity }}
</span>
<van-icon name="plus" class="text-gray-500 ml-2" />
此代码使用 van-icon
组件提供了减号和加号按钮,允许用户调整商品数量。当用户点击这些按钮时,会触发相应的方法来更新购物车中的商品数量。
4. 计算购物车总价
const cartTotal = ref(0);
computed: {
cartTotal: {
get() {
let total = 0;
cart.value.forEach((item) => {
total += item.price * item.quantity;
});
return total.toFixed(2);
},
},
},
此代码使用 Vue 的 computed
属性来计算购物车总价。它遍历购物车中的所有商品,并根据每个商品的价格和数量计算总价。
5. 购买按钮
<van-button
class="mt-4 w-full text-white bg-green-500 rounded-lg"
type="primary"
size="large"
>
Buy Now
</van-button>
此代码使用 van-button
组件提供了购买按钮。当用户点击此按钮时,会触发相应的事件处理程序来完成结账流程。
开发此购物篮卡片组件让我深入了解了 Vue 的响应式系统和组件化开发的优势。未来,该组件可以扩展和优化,以支持更多功能,例如: