import { defineStore } from 'pinia'; import { GoodsBean, StockBean } from '@/api/goods/types'; import { getCompanyId } from '@/utils'; const useShoppingCartStore = defineStore('shoppingCart', { state: (): { shoppingCartList: GoodsBean[] } => ({ shoppingCartList: uni.getStorageSync(`shoppingCart_${getCompanyId()}`) as GoodsBean[] }), persist: { // 修改存储中使用的键名称,默认为当前 Store的 id key: 'shoppingCartState', storage: { setItem(key, value) { uni.setStorageSync(key, value || []); // [!code warning] uni.setStorageSync(`shoppingCart_${getCompanyId()}`, JSON.parse(value).shoppingCartList); }, getItem(key) { return uni.getStorageSync(uni.getStorageSync(`shoppingCart_${getCompanyId()}`)); // [!code warning] } }, // 部分持久化状态的点符号路径数组,[]意味着没有状态被持久化(默认为undefined,持久化整个状态) paths: undefined }, getters: { getShoppingCartList(): GoodsBean[] { return this.shoppingCartList; }, totalCount(): number { return this.shoppingCartList.length; }, getSameGoodsIndex: (state) => (goodsId: string, colorId: string, sizeId: string) => { return state.shoppingCartList.findIndex(res => res.id === goodsId && res.checkedStock.colorId === colorId && res.checkedStock.sizeId === sizeId); } }, actions: { save(partial: Partial) { this.shoppingCartList.push(partial as GoodsBean); }, updateCount(index: number, count: number) { this.shoppingCartList[index].checkedStock.count += count; }, updateStock(index: number, stock: StockBean) { this.shoppingCartList[index].checkedStock = stock; }, delete(index: number) { this.shoppingCartList.splice(index, 1); }, deleteIfChecked() { this.shoppingCartList = this.shoppingCartList.filter(res => res.checked == undefined || res.checked === false); }, resetData() { this.shoppingCartList = uni.getStorageSync(`shoppingCart_${getCompanyId()}`); }, clearAll() { this.shoppingCartList = []; } } }); export default useShoppingCartStore;