cart.js
3.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import { ref, provide, inject, watchEffect } from 'vue'
import { useRouter } from 'vue-router'
const CartSymbol = Symbol()
export function provideCart() {
const router = useRouter()
const cartItems = ref([])
// 从localStorage加载购物车数据
try {
const storedCart = localStorage.getItem('cart')
if (storedCart) {
cartItems.value = JSON.parse(storedCart)
}
} catch (error) {
console.error('Failed to parse cart from localStorage:', error)
localStorage.removeItem('cart')
}
// 监听购物车变化并保存到localStorage
watchEffect(() => {
localStorage.setItem('cart', JSON.stringify(cartItems.value))
})
// 添加商品到购物车
function addToCart(item) {
const existingItemIndex = cartItems.value.findIndex(
i => i.id === item.id && i.type === item.type
)
if (existingItemIndex >= 0) {
const updatedItems = [...cartItems.value]
updatedItems[existingItemIndex] = {
...updatedItems[existingItemIndex],
quantity: updatedItems[existingItemIndex].quantity + 1
}
cartItems.value = updatedItems
} else {
cartItems.value = [...cartItems.value, { ...item, quantity: 1 }]
}
}
// 从购物车移除商品
function removeFromCart(itemId, itemType) {
cartItems.value = cartItems.value.filter(
item => !(item.id === itemId && item.type === itemType)
)
}
// 更新商品数量
function updateQuantity(itemId, itemType, quantity) {
if (quantity < 1) return
cartItems.value = cartItems.value.map(item =>
item.id === itemId && item.type === itemType
? { ...item, quantity }
: item
)
}
// 清空购物车
function clearCart() {
cartItems.value = []
}
// 获取购物车商品总数
function getItemCount() {
return cartItems.value.reduce((total, item) => total + item.quantity, 0)
}
// 计算购物车总价
function getTotalPrice() {
return cartItems.value.reduce(
(total, item) => total + item.price * item.quantity,
0
)
}
// 跳转到结账页面
function proceedToCheckout() {
if (cartItems.value.length > 0) {
router.push('/checkout')
}
}
// 处理结账流程
function handleCheckout(userData) {
// 构建订单数据
const orderData = {
items: cartItems.value.map(item => ({
id: item.id,
type: item.type,
quantity: item.quantity,
price: item.price,
title: item.title
})),
totalAmount: getTotalPrice(),
userData: userData,
orderDate: new Date().toISOString()
}
// TODO: 替换为实际的API调用
return new Promise((resolve) => {
// 模拟API调用
setTimeout(() => {
// 在实际应用中,这里应该调用后端API
console.warn('提交订单数据:', orderData)
// 订单提交成功后清空购物车
clearCart()
// 返回订单ID
resolve({
success: true,
orderId: 'ORD-' + Date.now(),
orderData: orderData
})
}, 1500)
})
}
const cart = {
items: cartItems,
addToCart,
removeFromCart,
updateQuantity,
clearCart,
getItemCount,
getTotalPrice,
proceedToCheckout,
handleCheckout
}
provide(CartSymbol, cart)
return cart
}
export function useCart() {
const cart = inject(CartSymbol)
if (!cart) {
throw new Error('useCart() must be used within a component that has called provideCart()')
}
return cart
}