2017-10-29 49 views
2

我正在學習VueJS並創建了這個小練習遊戲,以增強我對Vue的知識。如何在下一個事件循環中顯示警報?

http://jsfiddle.net/mzref4o0/1/

這種攻擊方法也將決出勝負:

attack: function(isSpecialAttack) { 
     let youHurt = Math.floor(Math.random() * 10); 
     let monsterHurt = Math.floor(Math.random() * 10); 
     if (isSpecialAttack) { 
     youHurt = Math.floor(Math.random() * (20 - 10 + 1)) + 10; 
     monsterHurt = Math.floor(Math.random() * (20 - 10 + 1)) + 10; 
     } 
     this.you.bloodLevel -= youHurt; 
     this.monster.bloodLevel -= monsterHurt; 

     this.messages.push([ 
     {id: this.getRandomId, turn: 'you', msg: 'PLAYER HTIS MONSTER FOR ' + monsterHurt}, 
     {id: this.getRandomId, turn: 'monster', msg: 'MONSTER HTIS PLAYER FOR ' + youHurt} 
     ]) 


     if (this.you.bloodLevel <= 0 || this.monster.bloodLevel <= 0) { 
     if (this.you.bloodLevel <= 0) { 
      alert('you lost'); 
     } else { 
      alert('you won'); 
     } 
     } 
    }, 

的問題是,警報消息顯示之前的「攻擊」開始,這意味着血條下降&的消息在顯示警告消息之後添加。只有在發生這兩件事情後,我如何才能讓警報顯示出來?

我認爲這個問題是由於事件循環...但這就是我所知道的。

+0

您是否嘗試過使用的承諾。就像在承諾中包裝功能,然後在調用它之後。執行消息推送。或者嘗試使用'nextTick()'。 [這裏是關於nextTick()的文檔](https://vuejs.org/v2/guide/reactivity.html) – zeidanbm

回答

0

你正在努力實現的不是真的alert一起工作。

alert方法阻塞了代碼的執行,因此瀏覽器在塊被釋放之前不會開始處理重新繪製。

溶液was suggested in other stackoverflow post.

我強烈建議使用更現代化的技術,如vue-js modals

無論如何,這個代碼塊應該工作:

if (this.you.bloodLevel <= 0 || this.monster.bloodLevel <= 0) { 
     if (this.you.bloodLevel <= 0) { 
     setTimeout("alert('you lost');", 1); 

     } else { 
     setTimeout("alert('you won');", 1); 

     } 
    } 
相關問題