77 lines
2.1 KiB
JavaScript
77 lines
2.1 KiB
JavaScript
"use strict";
|
|
const common_vendor = require("../common/vendor.js");
|
|
const useCartStore = common_vendor.defineStore("cart", () => {
|
|
const items = common_vendor.ref([]);
|
|
const checkedItems = common_vendor.computed(() => items.value.filter((item) => item.checked));
|
|
const totalAmount = common_vendor.computed(
|
|
() => checkedItems.value.reduce((sum, item) => sum + item.specData.totalPrice * item.quantity, 0)
|
|
);
|
|
async function fetchCart() {
|
|
try {
|
|
const { getCartList } = await "../api/cart.js";
|
|
const list = await getCartList();
|
|
items.value = list.map((item) => ({ ...item, checked: true }));
|
|
} catch {
|
|
}
|
|
}
|
|
function addToCart(item) {
|
|
items.value.push(item);
|
|
"../api/cart.js".then(({ addToCart: apiAdd }) => {
|
|
apiAdd({
|
|
productId: item.productId,
|
|
specDataId: item.specDataId,
|
|
quantity: item.quantity
|
|
}).catch(() => {
|
|
});
|
|
}).catch(() => {
|
|
});
|
|
}
|
|
function removeFromCart(id) {
|
|
const index = items.value.findIndex((item) => item.id === id);
|
|
if (index !== -1) {
|
|
items.value.splice(index, 1);
|
|
"../api/cart.js".then(({ deleteCartItem }) => {
|
|
deleteCartItem(id).catch(() => {
|
|
});
|
|
}).catch(() => {
|
|
});
|
|
}
|
|
}
|
|
function updateQuantity(id, quantity) {
|
|
const item = items.value.find((item2) => item2.id === id);
|
|
if (item) {
|
|
item.quantity = quantity;
|
|
"../api/cart.js".then(({ updateCartItem }) => {
|
|
updateCartItem(id, { quantity }).catch(() => {
|
|
});
|
|
}).catch(() => {
|
|
});
|
|
}
|
|
}
|
|
function toggleCheck(id) {
|
|
const item = items.value.find((item2) => item2.id === id);
|
|
if (item) {
|
|
item.checked = !item.checked;
|
|
}
|
|
}
|
|
function toggleCheckAll() {
|
|
const allChecked = items.value.every((item) => item.checked);
|
|
items.value.forEach((item) => {
|
|
item.checked = !allChecked;
|
|
});
|
|
}
|
|
return {
|
|
items,
|
|
checkedItems,
|
|
totalAmount,
|
|
fetchCart,
|
|
addToCart,
|
|
removeFromCart,
|
|
updateQuantity,
|
|
toggleCheck,
|
|
toggleCheckAll
|
|
};
|
|
});
|
|
exports.useCartStore = useCartStore;
|
|
//# sourceMappingURL=../../.sourcemap/mp-weixin/store/cart.js.map
|