[英]How to pass reactive data to Vue components using pinia store elements?
解构松果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"
/>
我正在尝试使用 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.