Javascript 将数据值更改为相同值时不会触发Vue watch

Javascript 将数据值更改为相同值时不会触发Vue watch,javascript,vue.js,Javascript,Vue.js,我正在创建一个UNO克隆,我使用了一个观察者在每次转弯开始时执行代码: 观察:{ //轮换 异步turnId(val){ const isUserTurn=val==0; if(isUserTurn){ //重置已绘制标志 //this.hasdrauded=false; }否则{ 等待setTimeout(()=>this.playAI(),1000); } }, }, 当轮到用户时,此代码将运行: wait setTimeout(()=>this.playAI(),1000); play

我正在创建一个UNO克隆,我使用了一个观察者在每次转弯开始时执行代码:

观察:{
//轮换
异步turnId(val){
const isUserTurn=val==0;
if(isUserTurn){
//重置已绘制标志
//this.hasdrauded=false;
}否则{
等待setTimeout(()=>this.playAI(),1000);
}
},
},
当轮到用户时,此代码将运行:

wait setTimeout(()=>this.playAI(),1000);
playAI方法是:

playAI(){
//拿着这张牌玩吧
这个。玩(牌)
},
玩(牌){
//玩这张牌(从手上删除并放在桩上)
this.nextTurn();
如果(card.value==='+4'){
这个.currentPlayer.hand.push(…这个.draw(4));
this.nextTurn();
}否则如果(card.value=='='+2'){
这个.currentPlayer.hand.push(…这个.draw(2));
this.nextTurn();
}否则,如果(card.value==='skip'){
this.nextTurn();
}
},
nextTurn(){
//如果回合id大于玩家总数,则将其备份
如果(this.turnId===this.playersNumber-1)this.turnId=0;
否则,该.turnId+=1;
},
问题是,当AI玩一张像skip这样的牌时,它会玩这张牌(skip),它会运行下一个回合方法两次(turnId+2),但是turnId上的观察者不会运行第二次,所以AI会停止玩

  • 这个错误只发生在AI回合,而不是用户的回合,所以我认为错误来自观察者
  • 我只对两名玩家进行了测试,因此当AI玩一张像skip这样的牌时,回合会回到他身上(它会改变,但返回的值与以前相同),因此这可能是错误,因为当方法停止运行时,turnId值与函数调用之前的值相同

如果这是一个错误,如何强制运行观察程序?

观察程序在事件循环中只执行一次,您应该以异步方式进行第二次调用


附加

例如:

    play(card) {
      // play the card (delete from hand and put on piletop)

      this.nextTurn();
      setTimeout(() => {
        if (card.value === '+4') {
          this.currentPlayer.hand.push(...this.draw(4));
          this.nextTurn();
        } else if (card.value === '+2') {
          this.currentPlayer.hand.push(...this.draw(2));
          this.nextTurn();
        } else if (card.value === 'skip') {
          this.nextTurn();
        }
      }, 0)
    }

这样,观察者将执行两次,但是它会导致意想不到的结果,并且你需要考虑如何调整

< P>我设法通过改变播放方法来解决这个问题:

玩(牌){
如果(card.value==='reverse'){//如果卡是反向的
this.isReversed=!this.isReversed;//反转标志
}else if(card.value==='skip'){//if卡为skip
this.skipTurn=true;//设置跳过标志
}else if(card.value==='+2'){//if card为+2
this.nextPlayer.hand.push(…this.draw(2));//nextPlayer绘制2
this.nextPlayer.hand.sort(this.sortHandler);//对绘图玩家的手进行排序
this.skipTurn=true;//设置跳过标志
}else if(card.value==='+4'){//if card为+4
this.nextPlayer.hand.push(…this.draw(4));//nextPlayer绘制4
this.nextPlayer.hand.sort(this.sortHandler);//对绘图玩家的手进行排序
this.skipTurn=true;//设置跳过标志
}
//下一轮
this.nextTurn();
}
  • 我创建了nextPlayer computed,它与currentPlayer做相同的事情,但在下一个上
  • 我还创建了一个标志,用于检查下一个玩家是否必须跳过该回合,并在“观察者”中进行检查:
turnId(转弯){
如果(此.skipTurn){
this.skipTurn=false;
this.nextTurn();
返回;
}
如果(回合!==0){//如果轮到机器人了
这个。playAI();
}
},

我该怎么做?