vue 儲存中的陣列在元件中不可用(及時)
P粉914731066
P粉914731066 2023-09-13 18:14:56
0
1
581

在我的應用程式中,我有一組遊戲卡,儲存在 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

誰能看看我該如何解決這個問題?

我不想在組件本身中獲取卡牌,因為我也想在其他組件中使用遊戲卡牌,而不是每次都從後端獲取它們。

P粉914731066
P粉914731066

全部回覆(1)
P粉652495194

如果在元件掛載時未填入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>

雖然預設觀察器僅在被觀察數組的完全重新分配時運行,但您可以在使用 深度觀察者(如果您需要的話)。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!