123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- // 管理游戏列表和通用游戏详情
- 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<IGame[]>([])
- const currentGame = ref<IGame | null>(null)
- const loading = ref(false)
- const error = ref<string | null>(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<IGame | null> {
- // 先从缓存中查找
- 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
- }
- })
|