67 lines
1.9 KiB
TypeScript
67 lines
1.9 KiB
TypeScript
import { pinia } from "@/pinia"
|
|
import { getShopGoodsApi } from "@@/apis/shop"
|
|
|
|
export interface Product {
|
|
id: number // 商品ID
|
|
name: string // 商品名称
|
|
price: number // 商品价格
|
|
stock: number // 商品库存
|
|
description: string // 商品描述
|
|
image: string // 商品图片URL
|
|
label: number // 商品标签
|
|
cellId: number // 商品所在的格子ID
|
|
}
|
|
|
|
export const useProductStore = defineStore("product", () => {
|
|
// 商品数据
|
|
const labels = ref<Array<{ id: number, name: string }>>([]);
|
|
const categories = ref<Product[]>([]);
|
|
const shopId = ref<number|null>(null);
|
|
|
|
const setShopId = (id: number|string) => {
|
|
shopId.value = Number(id);
|
|
getGoods();
|
|
}
|
|
|
|
const getGoods = async () => {
|
|
const urlParams = new URLSearchParams(window.location.search);
|
|
const shopIdParams = urlParams.get('shopId') || undefined;
|
|
if (shopIdParams) {
|
|
shopId.value = Number(shopIdParams);
|
|
}
|
|
|
|
try {
|
|
const { data } = await getShopGoodsApi(shopId.value);
|
|
|
|
// 转换分类标签
|
|
labels.value = data.categoryList.map(c => ({
|
|
id: c.categoryId, // 使用分类名称生成ID
|
|
name: c.categoryName
|
|
}))
|
|
|
|
// 转换商品数据
|
|
categories.value = data.goodsList.map(g => ({
|
|
id: g.goodsId,
|
|
name: g.goodsName,
|
|
price: g.price,
|
|
stock: g.stock,
|
|
description: g.goodsDetail || "暂无描述",
|
|
image: g.coverImg,
|
|
label: g.categoryId,
|
|
cellId: g.cellId
|
|
}))
|
|
} catch (error) {
|
|
console.error("获取商品数据失败:", error)
|
|
}
|
|
}
|
|
return { labels, categories, shopId, getGoods, setShopId }
|
|
})
|
|
|
|
/**
|
|
* @description 在 SPA 应用中可用于在 pinia 实例被激活前使用 store
|
|
* @description 在 SSR 应用中可用于在 setup 外使用 store
|
|
*/
|
|
export function useProductStoreOutside() {
|
|
return useProductStore(pinia)
|
|
}
|