簡體   English   中英

如何使用 pinia 存儲元素將反應數據傳遞給 Vue 組件?

[英]How to pass reactive data to Vue components using pinia store elements?

  • 游戲頁面.vue

解構松果state元件及作用方法

const $store = useGameStore();
const {game, teamOne, teamTwo} = storeToRefs($store);
const { getGame } = $store;

將破壞的變量傳遞給組件

<player-stat-table
  :title="teamTwo.name"
  :players="teamTwo.players"
  :teamColor="teamTwo.team_color"
 />
  • 表格顯示

桌子

  • 商店/game_store.js

我正在嘗試使用 updatePlayer 操作編輯上表中的數據,在成功完成操作后,我正在通過調用 get 操作方法來更新整個商店數據。 但是表中的數據並沒有被動更新,而是在頁面重新加載后更新。 如何反應性地更新它?

import { api } from 'boot/axios'
import { defineStore } from 'pinia'

import { splitPlayers } from 'src/helpers'

export const useGameStore = defineStore('game', {
  state: () => ({
    game: null,
    teamOne: null,
    teamTwo: null,
  }),

  getters: {
    getTeamOne: state => state.teamOne,
    getTeamTwo: state => state.teamTwo,
    getGameData: state => state.game,
  },

  actions: {
    getGame(payload) {
      return new Promise((resolve, reject) => {
        api.get(`/games/${payload.gameID}/`)
        .then(resp => {
          const data = resp.data;
          const teams = splitPlayers(data)
          this.game = data
          this.teamOne = teams[0]
          this.teamTwo = teams[1]
          resolve(data)
        })
      })
    },
    updatePlayer(payload) {
      return new Promise((resolve, reject) => {
        api.put(`/playerstat/${payload.id}/`, data)
        .then(resp => {
          const data = resp.data;
          this.getGame({gameID: data.game})
          resolve(data)
        })
      })
    },
  }
})

首先,你可以擺脫你的吸氣劑,因為pinia 文檔

作為吸氣劑,您可以將其視為計算屬性

你沒有計算任何東西。 因此,您可以簡單地訪問 state 屬性,您已經在 GamePage.vue 文件中執行此操作。

其次,您的操作似乎是異步的,但沒有標有“異步”。 您還應該考慮 async/await 模式而不是 Promiste.then()。

您還應該考慮使用 pinia 商店的“composition-api”方式,這反映了比使用“options API”方式更好的反應性。

 import { api } from 'boot/axios' import { defineStore } from 'pinia' import { splitPlayers } from 'src/helpers' export const useGameStore = defineStore('game', () => { const game = ref(null); const teamOne = ref(null); const teamTwo = ref(null); const getGame = async (gameId) => { const resp = await api.get(`/games/${gameId}/`); const teams = splitPlayers(resp.data) game.value = resp.data teamOne.value = teams[0] teamTwo.value = teams[1] }; const updatePlayer = async (data) => { const resp = await api.put(`/playerstat/${data.id}/`, data) const gameId = resp.data.game; await getGame(gameId) }; return { game, teamOne, teamTwo, getGame, updatePlayer } });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM