// 管理游戏列表和通用游戏详情 import { defineStore } from 'pinia' import { ref, computed } from 'vue' import { gameService} from '@/services/api/game' import { IGame } from '@/types/game' export const useGameStore = defineStore('game', () => { // 状态 const games = ref([]) const currentGame = ref(null) const loading = ref(false) const error = ref(null) // 计算属性 const hotGames = computed(() => games.value.filter(game => game.isHot)) const newGames = computed(() => games.value.filter(game => game.isNew)) // 获取游戏列表 async function fetchGames() { loading.value = true error.value = null try { const response = await gameService.getGames() if (response.success && response.data) { games.value = response.data } else { error.value = response.message || '获取游戏列表失败' games.value = [] } } catch (e) { console.error('获取游戏列表失败:', e) error.value = '获取游戏列表失败' games.value = [] } finally { loading.value = false } } // 获取游戏详情 async function getGameDetail(id: string): Promise { // 先从缓存中查找 const cachedGame = games.value.find(game => game.id === id) if (cachedGame) { currentGame.value = cachedGame return cachedGame } // 如果缓存中没有,从API获取 loading.value = true error.value = null try { const response = await gameService.getGameDetail(id) if (response.success && response.data) { currentGame.value = response.data return response.data } else { error.value = response.message || '获取游戏详情失败' currentGame.value = null return null } } catch (e) { console.error('获取游戏详情失败:', e) error.value = '获取游戏详情失败' currentGame.value = null return null } finally { loading.value = false } } // 设置当前游戏 function setCurrentGame(game: IGame | null) { currentGame.value = game } // 清除游戏数据 function clearGames() { games.value = [] currentGame.value = null error.value = null } return { // 状态 games, currentGame, loading, error, // Getters hotGames, newGames, // 方法 fetchGames, getGameDetail, setCurrentGame, clearGames } })