2017-10-29 59 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); 

     } 
    }