wangzhibo
4 天以前 10595d8632f959d0954d1939243196f4eed02372
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import { storage } from "/@/cool";
import { uuid } from "/@/cool/utils";
 
// 购物车
export const useShoppingCart = defineStore("shopping-cart", () => {
    const list = ref<OrderGoods[]>(storage.get("shopping-cart.list") || []);
 
    // 购物车数量
    const num = computed(() => {
        return list.value.length;
    });
 
    // 数量+1
    function add(data: OrderGoods) {
        const d = list.value.find((e) => e.spec?.id == data.spec?.id);
 
        if (d) {
            // 判定库存
            d.count += data.count || 1;
 
            if (d.count > data.spec.stock!) {
                d.count = data.spec.stock || 1;
            }
        } else {
            list.value.push({
                ...data,
                id: uuid(),
            });
        }
    }
 
    // 删除规格
    function del(id: string) {
        const i = list.value.findIndex((e) => e.id == id);
 
        if (i >= 0) {
            list.value.splice(i, 1);
        }
    }
 
    // 删除规格根据 specId
    function delBySpecId(id: number) {
        const i = list.value.findIndex((e) => e.spec?.id == id);
 
        if (i >= 0) {
            list.value.splice(i, 1);
        }
    }
 
    // 监听更新
    watch(
        list,
        (val) => {
            storage.set("shopping-cart.list", val);
        },
        {
            deep: true,
        },
    );
 
    return {
        list,
        num,
        add,
        del,
        delBySpecId,
    };
});