用vue实现简易购物车
实现简易购物车的Vue代码
以下是一个基于Vue 3的简易购物车实现方案,包含商品展示、添加删除、价格计算等核心功能。
项目结构
src/
├── components/
│ ├── CartItem.vue
│ └── ProductList.vue
├── App.vue
└── main.js
核心代码实现
App.vue(主组件)

<template>
<div class="app">
<h1>简易购物车</h1>
<ProductList :products="products" @add-to-cart="addToCart" />
<div class="cart">
<h2>购物车 ({{ cartItems.length }})</h2>
<CartItem
v-for="item in cartItems"
:key="item.id"
:item="item"
@remove-from-cart="removeFromCart"
/>
<div class="total">总计: ¥{{ totalPrice.toFixed(2) }}</div>
</div>
</div>
</template>
<script>
import ProductList from './components/ProductList.vue'
import CartItem from './components/CartItem.vue'
export default {
components: { ProductList, CartItem },
data() {
return {
products: [
{ id: 1, name: '商品A', price: 100 },
{ id: 2, name: '商品B', price: 200 },
{ id: 3, name: '商品C', price: 300 }
],
cartItems: []
}
},
computed: {
totalPrice() {
return this.cartItems.reduce((total, item) => total + item.price * item.quantity, 0)
}
},
methods: {
addToCart(product) {
const existingItem = this.cartItems.find(item => item.id === product.id)
if (existingItem) {
existingItem.quantity++
} else {
this.cartItems.push({ ...product, quantity: 1 })
}
},
removeFromCart(itemId) {
this.cartItems = this.cartItems.filter(item => item.id !== itemId)
}
}
}
</script>
<style>
.app {
display: flex;
gap: 2rem;
padding: 2rem;
}
.cart {
border: 1px solid #ddd;
padding: 1rem;
min-width: 300px;
}
.total {
font-weight: bold;
margin-top: 1rem;
}
</style>
ProductList.vue(商品列表组件)

<template>
<div class="product-list">
<h2>商品列表</h2>
<div v-for="product in products" :key="product.id" class="product">
<span>{{ product.name }} - ¥{{ product.price }}</span>
<button @click="$emit('add-to-cart', product)">加入购物车</button>
</div>
</div>
</template>
<script>
export default {
props: ['products']
}
</script>
<style>
.product {
margin: 0.5rem 0;
padding: 0.5rem;
border: 1px solid #eee;
display: flex;
justify-content: space-between;
}
</style>
CartItem.vue(购物车商品项组件)
<template>
<div class="cart-item">
<span>{{ item.name }} x {{ item.quantity }}</span>
<span>¥{{ (item.price * item.quantity).toFixed(2) }}</span>
<button @click="$emit('remove-from-cart', item.id)">删除</button>
</div>
</template>
<script>
export default {
props: ['item']
}
</script>
<style>
.cart-item {
display: flex;
justify-content: space-between;
margin: 0.5rem 0;
}
</style>
功能扩展建议
- 数量调整:在购物车商品项中添加增减数量的按钮
- 本地存储:使用localStorage保存购物车状态
- 商品搜索:添加搜索框过滤商品列表
- 分类展示:按商品分类展示商品
- 结算功能:添加结算按钮和流程
运行项目
创建Vue项目后,将上述代码放入对应文件,运行以下命令:
npm install
npm run dev
这个实现包含了购物车的核心功能,可以根据实际需求进一步扩展和完善。





