本代码段展示了如何在 Vue.js 中实现一个购物车功能,用户可以添加、删除和修改购物车中的商品,并实时计算总价。
1. 定义购物车数据模型
const cart = ref([
{
id: 1,
name: "White T-Shirt",
description: "A classic white t-shirt is a staple in any wardrobe.",
image: "https://source.unsplash.com/random/80x80",
price: 10,
quantity: 1,
},
// ...
]);
2. 渲染购物车列表
<div class="mt-4">
<van-cell v-for="item in cart" :key="item.id" title="" is-link clickable>
<template #title>
<!-- 商品信息 -->
</template>
<template #right>
<!-- 商品数量和价格 -->
</template>
</van-cell>
</div>
3. 修改商品数量
<van-stepper
v-model="item.quantity"
:min="1"
:max="10"
:step="1"
size="small"
/>
4. 计算总价
const total = ref(0);
5. 结账
<van-button
round
block
type="primary"
class="mt-4"
:style="{ backgroundColor: '#FFD700' }"
>
Checkout
</van-button>
通过实现这段代码,我们掌握了 Vue.js 中购物车功能的基本实现。未来,我们可以对该功能进行以下拓展和优化: