game.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. // 管理游戏列表和通用游戏详情
  2. import { defineStore } from 'pinia'
  3. import { ref, computed } from 'vue'
  4. import { gameService} from '@/services/api/game'
  5. import { IGame } from '@/types/game'
  6. export const useGameStore = defineStore('game', () => {
  7. // 状态
  8. const games = ref<IGame[]>([])
  9. const currentGame = ref<IGame | null>(null)
  10. const loading = ref(false)
  11. const error = ref<string | null>(null)
  12. // 计算属性
  13. const hotGames = computed(() => games.value.filter(game => game.isHot))
  14. const newGames = computed(() => games.value.filter(game => game.isNew))
  15. // 获取游戏列表
  16. async function fetchGames() {
  17. loading.value = true
  18. error.value = null
  19. try {
  20. const response = await gameService.getGames()
  21. if (response.success && response.data) {
  22. games.value = response.data
  23. } else {
  24. error.value = response.message || '获取游戏列表失败'
  25. games.value = []
  26. }
  27. } catch (e) {
  28. console.error('获取游戏列表失败:', e)
  29. error.value = '获取游戏列表失败'
  30. games.value = []
  31. } finally {
  32. loading.value = false
  33. }
  34. }
  35. // 获取游戏详情
  36. async function getGameDetail(id: string): Promise<IGame | null> {
  37. // 先从缓存中查找
  38. const cachedGame = games.value.find(game => game.id === id)
  39. if (cachedGame) {
  40. currentGame.value = cachedGame
  41. return cachedGame
  42. }
  43. // 如果缓存中没有,从API获取
  44. loading.value = true
  45. error.value = null
  46. try {
  47. const response = await gameService.getGameDetail(id)
  48. if (response.success && response.data) {
  49. currentGame.value = response.data
  50. return response.data
  51. } else {
  52. error.value = response.message || '获取游戏详情失败'
  53. currentGame.value = null
  54. return null
  55. }
  56. } catch (e) {
  57. console.error('获取游戏详情失败:', e)
  58. error.value = '获取游戏详情失败'
  59. currentGame.value = null
  60. return null
  61. } finally {
  62. loading.value = false
  63. }
  64. }
  65. // 设置当前游戏
  66. function setCurrentGame(game: IGame | null) {
  67. currentGame.value = game
  68. }
  69. // 清除游戏数据
  70. function clearGames() {
  71. games.value = []
  72. currentGame.value = null
  73. error.value = null
  74. }
  75. return {
  76. // 状态
  77. games,
  78. currentGame,
  79. loading,
  80. error,
  81. // Getters
  82. hotGames,
  83. newGames,
  84. // 方法
  85. fetchGames,
  86. getGameDetail,
  87. setCurrentGame,
  88. clearGames
  89. }
  90. })