从 vueJS 方法调用的 setTimeout() 不起作用

新手上路,请多包涵

我正在尝试允许用户从应用程序重置或关闭给定服务器。我现在正在处理界面,并希望向用户提供有关正在发生的事情的消息。我显示在我的数据对象中定义的消息以指示所采取的操作。然后我使用 setTimeout 来切换重置….消息和重置消息。请参阅以下方法。

     systemReset: function(){
            this.message = this.server + ': Resetting';
            setTimeout(function(){
                this.message = this.server + ': Reset';
            }, 2000);

    }

在我的浏览器中,我可以触发此消息并显示我的“重置”消息,但永远不会输出以下“重置”消息。我有任何格式错误吗?

将此方法放在上下文中是我的整个组件。

   <template>
    <div>
      <p>{{message}}</p>
      <button @click="systemReset">Reset Server</button>
      <button @click="systemPowerDown">Poweroff Server</button>
    </div>
  </template>

  <script type="text/javascript">
    export default{
      data: function(){
        return{
          message: ''
        }
      },
      methods: {
        systemPowerDown: function(){
            this.message = this.server + ': Server Down';
        },
        systemReset: function(){
            this.message = this.server + ': Resetting';
            setTimeout(function(){
                this.message = this.server + ': Reset';
            }, 2000);
         }
      },
      props: ['server']
    }
  </script>

Am I missing something obvious?  Or is there some vue limitation I am unaware of?

原文由 DMrFrost 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 887
2 个回答

--- 的值在 this setTimeout 是不同的。

如果你使用的是 ES6,你可以使用箭头函数:

 setTimeout(() => { this.message = this.server + ': Reset' }, 2000)

或者,如果您不是,则可以绑定 this 的值:

 setTimeout(function () {
  this.message = this.server + ': Reset'
}.bind(this))

但是,由于从未使用过 Vue,我不知道当您更改 this.message 的值时它是否会知道重新渲染,或者您是否应该更改某些组件状态或其他内容。

原文由 Tommy Brunn 发布,翻译遵循 CC BY-SA 3.0 许可协议

因为您在 setTimeout 中, this 与您的 Vue 实例不对应。您可以使用 self 代替:

 systemReset: function(){
    this.message = this.server + ': Resetting';
    var self = this;
    setTimeout(function(){
        self.message = self.server + ': Reset';
    }, 2000);
}

原文由 Treast 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题