Files
suke-mp/src/store/modules/shoppingcart/index.ts
2024-04-14 16:43:43 +08:00

72 lines
2.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<GoodsBean>) {
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;