使用Vue3实现简单购物车应用
随着电子商务的迅猛发展,购物车作为一个核心功能,几乎在每个在线商店中都不可或缺。本篇文章将带你一步步使用Vue 3的setup语法糖来开发一个简单的购物车应用,功能包括添加商品、删除商品,以及计算总价。
1. 项目概述
我们的购物车应用允许用户:
- 添加商品到购物车
- 删除购物车中的商品
- 计算购物车中所有商品的总价
在开始之前,请确保你已经安装了Vue 3的开发环境。如果未安装,可以使用Vue CLI快速搭建一个新项目。
npm install -g @vue/cli
vue create shopping-cart
cd shopping-cart
npm run serve
2. 项目结构
在src
目录下,我们将创建以下几个组件:
App.vue
:主组件Cart.vue
:购物车组件ProductList.vue
:产品列表组件
3. 实现产品列表组件
首先,我们来实现ProductList.vue
,这个组件将展示可供选择的产品。
<!-- src/components/ProductList.vue -->
<template>
<div>
<h2>产品列表</h2>
<div v-for="product in products" :key="product.id" class="product">
<span>{{ product.name }}</span>
<span>价格: ¥{{ product.price.toFixed(2) }}</span>
<button @click="addToCart(product)">添加到购物车</button>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
const products = ref([
{ id: 1, name: '商品1', price: 100 },
{ id: 2, name: '商品2', price: 200 },
{ id: 3, name: '商品3', price: 300 },
]);
const addToCart = (product) => {
const event = new CustomEvent('add-to-cart', {
detail: product,
bubbles: true
});
window.dispatchEvent(event);
};
</script>
<style scoped>
.product {
margin-bottom: 20px;
}
button {
margin-left: 10px;
}
</style>
以上代码创建了一个产品列表,并添加了“添加到购物车”按钮。该按钮用于将选定的商品通过事件发送到购物车组件。
4. 实现购物车组件
接下来,我们实现Cart.vue
组件,在这里我们将管理购物车的状态,包括添加、删除商品及计算总价。
<!-- src/components/Cart.vue -->
<template>
<div>
<h2>购物车</h2>
<div v-if="cart.length === 0">购物车为空</div>
<div v-else>
<div v-for="(item, index) in cart" :key="index" class="cart-item">
<span>{{ item.name }}</span>
<span>价格: ¥{{ item.price.toFixed(2) }}</span>
<button @click="removeFromCart(index)">删除</button>
</div>
<h3>总价格: ¥{{ totalPrice.toFixed(2) }}</h3>
</div>
</div>
</template>
<script setup>
import { ref, computed } from 'vue';
const cart = ref([]);
const addToCart = (product) => {
cart.value.push(product);
};
const removeFromCart = (index) => {
cart.value.splice(index, 1);
};
const totalPrice = computed(() => {
return cart.value.reduce((sum, item) => sum + item.price, 0);
});
// 监听“添加到购物车”事件
window.addEventListener('add-to-cart', (event) => {
addToCart(event.detail);
});
</script>
<style scoped>
.cart-item {
margin-bottom: 10px;
}
button {
margin-left: 10px;
}
</style>
在该组件中,我们定义了一个响应式的cart
数组来存储购物车中的商品。通过一个computed
属性,我们计算出购物车中所有商品的总价。同时,当用户点击删除按钮时,可以从购物车中删除相应的商品。
5. 在主组件中使用购物车和产品列表
最后,我们将ProductList
和Cart
组件引入到App.vue
中,并使其在页面中显示。
<!-- src/App.vue -->
<template>
<div id="app">
<h1>购物车应用</h1>
<ProductList />
<Cart />
</div>
</template>
<script setup>
import ProductList from './components/ProductList.vue';
import Cart from './components/Cart.vue';
</script>
<style>
#app {
max-width: 600px;
margin: auto;
}
</style>
6. 完整代码和测试
现在,我们已经完成了一个简单的购物车应用。确保项目能够正常运行,使用以下命令启动开发服务器:
npm run serve
访问http://localhost:8080
,你将看到产品列表。点击“添加到购物车”按钮后,选定的商品将出现在购物车中,同时总价也会自动更新。你可以尝试删除购物车中的商品,以验证应用程序的功能是否正常。
总结
在这篇文章中,我们通过使用Vue 3的setup语法糖构建了一个简单的购物车应用。我们实现了以下功能:
- 显示产品列表
- 添加商品到购物车
- 从购物车中删除商品
- 计算购物车中商品的总价格
这只是一个基本示例,你可以在此基础上进行扩展,比如添加商品数量、实现持久化存储(使用localStorage
或Vuex
),或美化界面等。