在我的应用程序中,我有一组游戏卡,存储在 vuex 商店中。
玩家填写一个游戏引脚,代码会检查它,并获取该引脚的游戏卡并将它们存储在存储中并打开内存组件:
checkPinExists(){
//this.$store.dispatch('retrieveGameByPin', this.enteredPin)
this.retrieveGameByPin(this.enteredPin)
.then(res => {
this.fetchGameCards(this.currentGame.id); // als spel bestaat de bijbehorende kaarten in de store opslaan
this.currentGameError = false; // dus als we hier zijn is er geen gameerror...
this.checked= true;
if (this.currentGame.game_status === 'actief'){
this.$router.push("memory");
}
})
.catch(err => {
this.currentGameError = true;
console.error(err);
});
}
fetchGameCrds 是一个 vuex 操作:
export const fetchGameCards = ({commit}, game_id) => {
return new Promise((resolve, reject) => {
let status = '';
let data ={};
console.log("fetching gameCards ");
fetch(`api/cardsByGame/${game_id}`)
.then(async res => {
status = res.status;
if(status === 200) {
data = await res.json();
}
else {
data =null;
}
})
.then(res=>{
if ( status === 200) {
commit('SET_GAME_CARDS', data);
resolve('GameKaarten gevonden');
}
else {
reject('Geen gamekaartenkaart beschikbaar');
}
});
});
}
在记忆组件中,卡片被检索并开始游戏。 不幸的是我无法及时从商店拿到游戏卡。
在浏览器的开发人员窗格中,我确实看到卡片在商店中。
Memoryscript 以一些调试消息开始:
<script>
import { mapState, mapActions } from 'vuex';
export default {
mounted() {
console.log("at mounted show GameCards:"),
console.log(this.gameCards);
this.createDeck(),
this.createShowCards()
},
computed: {
...mapState([
'currentSpeler' ,'currentSpelerCard', 'currentGame', 'gameCards'
]),
控制台中的输出有点像:
at mounted show GameCards: [Handler]]: Array(0) length: 0
谁能看看我该如何解决这个问题?
我不想在组件本身中获取卡牌,因为我也想在其他组件中使用游戏卡牌,而不是每次都从后端获取它们。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果在组件挂载时未填充
gameCards数组,您可以使用 观察者 在gameCards实际准备好使用时运行您的函数watch: { // whenever gameCards is assigned a new value, this function will run gameCards(newValue, oldValue) { // only do this after first assignment (when gameCards is initially empty) if(oldValue.length === 0) { this.createDeck() this.createShowCards() } } },当分配新的数组值时,观察程序将始终运行,但正如我的代码示例所示,您可以使用基于传入的新旧数组值的逻辑来控制观察程序是否实际执行任何操作。 p>
虽然默认情况下观察器仅在被观察数组的完全重新分配时运行,但您可以在使用 深度观察者(如果您需要的话)。