在我的应用程序中,我有一组游戏卡,存储在 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
任何人都可以看到我如何解决这个问题吗?
我不想在组件本身中获取卡片,因为我也想在其他组件中使用游戏卡片,而不是每次都从后端获取它们..
如果
gameCards
数组在您的组件的安装时间没有填充,您可以使用 watcher 来运行您的函数,只要 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()
}
}
},
watcher 将始终在分配新数组值时运行,但正如我的代码示例所示,您可以通过使用基于传入的新旧数组值的逻辑来控制 watcher 是否实际执行任何操作。
虽然默认情况下观察器仅在被观察数组的完全重新分配时运行,但您可以通过使用 deep watcher 代替(如果您需要的话)在修改单个数组对象时运行它。