一个完整的购物车系统需要包含以下核心功能:
商品展示模块
购物车操作模块
计算模块
持久化存储
技术栈 | 用途说明 | 版本 |
---|---|---|
Vue3 | 核心框架 | 3.4+ |
Pinia | 状态管理 | 2.1+ |
Element Plus | UI组件库 | 2.4+ |
Vue-Router | 路由管理 | 4.2+ |
src/
├── stores/
│ └── cart.js # 购物车状态管理
├── components/
│ ├── ProductList.vue # 商品列表
│ └── CartPanel.vue # 购物车面板
├── views/
│ ├── HomeView.vue # 主页面
│ └── DetailView.vue # 商品详情页
└── utils/
└── storage.js # 本地存储工具
// stores/cart.js
import { defineStore } from 'pinia'
import { useStorage } from '@/utils/storage'
export const useCartStore = defineStore('cart', {
state: () => ({
items: useStorage('cart_items', []), // 持久化存储
selected: new Set() // 选中的商品ID
}),
actions: {
// 添加商品
addItem(product, specs = {}, quantity = 1) {
const existing = this.items.find(
item => item.id === product.id &&
JSON.stringify(item.specs) === JSON.stringify(specs)
)
if (existing) {
existing.quantity += quantity
} else {
this.items.push({
...product,
specs,
quantity,
id: `${product.id}-${Date.now()}` // 生成唯一ID
})
}
},
// 更新数量
updateQuantity(id, newQuantity) {
const item = this.items.find(i => i.id === id)
if (item) {
item.quantity = Math.max(1, newQuantity)
}
},
// 删除商品
removeItem(id) {
this.items = this.items.filter(i => i.id !== id)
this.selected.delete(id)
},
// 切换选择状态
toggleSelect(id) {
if (this.selected.has(id)) {
this.selected.delete(id)
} else {
this.selected.add(id)
}
},
// 全选/取消全选
toggleAll(checked) {
if (checked) {
this.items.forEach(i => this.selected.add(i.id))
} else {
this.selected.clear()
}
}
},
getters: {
// 计算总金额
totalAmount: (state) => {
return state.items.reduce((sum, item) => {
if (state.selected.has(item.id)) {
return sum + item.price * item.quantity
}
return sum
}, 0).toFixed(2)
},
// 选中商品总数
selectedCount: (state) => state.selected.size
}
})
{{ product.name }}
¥{{ product.price }}
加入购物车
全选({{ selectedCount }})
清空购物车
toggleSelect(item.id, val)"
/>
{{ item.name }}
规格:{{ formatSpecs(item.specs) }}
updateQuantity(item.id, val)"
/>
¥{{ (item.price * item.quantity).toFixed(2) }}
// utils/storage.js
export const useStorage = (key, defaultValue) => {
const val = ref(JSON.parse(localStorage.getItem(key))
watch(val, (newVal) => {
localStorage.setItem(key, JSON.stringify(newVal))
}, { deep: true })
return val.value || defaultValue
}
computed
缓存计算结果// 在store action中添加错误处理
try {
// 业务逻辑
} catch (error) {
ElNotification.error({
title: '操作失败',
message: error.message
})
throw error
}
// 在store中添加
async syncCart() {
const { data } = await axios.post('/api/cart/sync', {
items: this.items
})
this.items = data.cartItems
}
// 在getters中添加
discountedAmount: (state) => (coupon) => {
const total = state.totalAmount
if (coupon.type === 'percent') {
return total * (1 - coupon.value)
}
return total - coupon.value
}
组件拆分原则
语法状态管理规范
用户体验优化
通过本教程你可以掌握:
✅ Vue3组合式API开发模式
✅ Pinia状态管理实战技巧
✅ 电商购物车核心业务逻辑
✅ 前端性能优化常见手段
后续改进方向:
欢迎在评论区留下你的问题和建议!如果觉得有帮助,请点赞收藏支持作者~