From cb185f0362da984f2b611ea1cf119315d9a63623 Mon Sep 17 00:00:00 2001 From: qinhan Date: Fri, 10 Apr 2026 15:41:32 +0800 Subject: [PATCH] feat(game): add bag store --- Build_God_Game/src/stores/bag.ts | 86 ++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 Build_God_Game/src/stores/bag.ts diff --git a/Build_God_Game/src/stores/bag.ts b/Build_God_Game/src/stores/bag.ts new file mode 100644 index 0000000..9ad5205 --- /dev/null +++ b/Build_God_Game/src/stores/bag.ts @@ -0,0 +1,86 @@ +import { defineStore } from 'pinia' +import { ref, computed } from 'vue' +import { getCharacterBag, getBagItems, type CharacterBag, type BagItem } from '@/api/bag' +import { useCharacterStore } from './character' + +const PAGE_SIZE = 16 + +export const useBagStore = defineStore('bag', () => { + const characterStore = useCharacterStore() + + const characterBag = ref(null) + const bagItems = ref([]) + const currentPage = ref(1) + const loading = ref(false) + const error = ref(null) + + const currentCharacterId = computed(() => characterStore.currentCharacter?.id) + + const totalItems = computed(() => bagItems.value.length) + + const totalPages = computed(() => Math.ceil(totalItems.value / PAGE_SIZE)) + + const paginatedItems = computed(() => { + const start = (currentPage.value - 1) * PAGE_SIZE + const end = start + PAGE_SIZE + return bagItems.value.slice(start, end) + }) + + const usedCapacity = computed(() => { + return bagItems.value.reduce((sum, item) => sum + item.quantity, 0) + }) + + const loadBag = async () => { + if (!currentCharacterId.value) { + error.value = '请先选择角色' + return + } + + try { + loading.value = true + error.value = null + + characterBag.value = await getCharacterBag(currentCharacterId.value) + + if (characterBag.value) { + bagItems.value = await getBagItems(characterBag.value.id) + } else { + bagItems.value = [] + } + + currentPage.value = 1 + } catch (e: any) { + error.value = e.message || '加载背包失败' + console.error('Load bag error:', e) + } finally { + loading.value = false + } + } + + const nextPage = () => { + if (currentPage.value < totalPages.value) { + currentPage.value++ + } + } + + const prevPage = () => { + if (currentPage.value > 1) { + currentPage.value-- + } + } + + return { + characterBag, + bagItems, + currentPage, + totalPages, + totalItems, + paginatedItems, + usedCapacity, + loading, + error, + loadBag, + nextPage, + prevPage + } +}) \ No newline at end of file