shop-web/src/pinia/stores/product.ts

56 lines
1.5 KiB
TypeScript
Raw Normal View History

2025-03-05 09:22:29 +08:00
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
2025-03-08 08:09:31 +08:00
label: number // 商品标签
cellId: number // 商品所在的格子ID
2025-03-05 09:22:29 +08:00
}
export const useProductStore = defineStore("product", () => {
// 商品数据
2025-03-08 08:09:31 +08:00
const labels = ref<Array<{ id: number, name: string }>>([])
const categories = ref<Product[]>([])
2025-03-05 09:22:29 +08:00
const getGoods = async () => {
try {
const { data } = await getShopGoodsApi()
2025-03-08 08:09:31 +08:00
2025-03-05 09:22:29 +08:00
// 转换分类标签
labels.value = data.categoryList.map(c => ({
id: c.categoryId, // 使用分类名称生成ID
name: c.categoryName
}))
2025-03-08 08:09:31 +08:00
2025-03-05 09:22:29 +08:00
// 转换商品数据
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
2025-03-05 09:22:29 +08:00
}))
} catch (error) {
2025-03-08 08:09:31 +08:00
console.error("获取商品数据失败:", error)
2025-03-05 09:22:29 +08:00
}
}
2025-03-08 08:09:31 +08:00
getGoods()
return { labels, categories, getGoods }
2025-03-05 09:22:29 +08:00
})
/**
* @description SPA pinia 使 store
* @description SSR setup 使 store
*/
export function useProductStoreOutside() {
return useProductStore(pinia)
}