Browse Source

feat(game): add bag store

master
qinhan 1 month ago
parent
commit
cb185f0362
  1. 86
      Build_God_Game/src/stores/bag.ts

86
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<CharacterBag | null>(null)
const bagItems = ref<BagItem[]>([])
const currentPage = ref(1)
const loading = ref(false)
const error = ref<string | null>(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
}
})
Loading…
Cancel
Save