setTimeout() 无法从 vueJS 方法调用

问题描述 投票:0回答:5

我试图允许用户从应用程序重置或关闭给定服务器。我现在正在开发界面,并希望向用户提供有关正在发生的事情的消息。我显示数据对象中定义的消息来指示所采取的操作。然后,我使用 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?  
javascript methods vue.js
5个回答
46
投票

this
内部
setTimeout
的值是不同的。

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

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

或者如果你不是,你可以绑定

this
的值:

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

但是,由于从未使用过 Vue,我不知道当你更改

this.message
的值时它是否会知道重新渲染,或者是否应该更改某些组件状态或其他内容。


6
投票

因为您位于

setTimeout
内,所以
this
与您的 Vue 实例不对应。您可以使用
self
代替 :

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

2
投票

可以通过将

this
存储在超时函数之外的变量中来解决吗?

像这样:

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

这样做指的是正确的功能

systemReset


0
投票

我遇到了一个熟悉的问题。 因此,解决方案是创建一个更改变量的函数(在“方法”中)。 然后从“setInterval”我调用了这个方法(this.methodname)。


0
投票

如果没有帮助,请使用 $forceUpdate()

this
到 setTimeout() 的适当段落在 JSFiddle 中工作正常 https://jsfiddle.net/BeloglazovRL/owL94phz/(Vue 2.6.14)。 但它不适用于我使用 Vue 2.6.13 的 Web 应用程序。

调用 Vue

this.$forceUpdate();
帮助我定期调用
setTimeout()

我厌倦了所有其他答案:将

this
保存到
self
、箭头函数和显式绑定。 调试输出打印了正在变化的变量并使用 Vue 内部内容纠正了
this
,但屏幕上没有任何变化。仅在计时器结束后才发生变化。 我尝试将超时设置为 5 秒而不是 1 秒。这也没有帮助。 然后我决定强制更新。例如:你能强制 Vue.js 重新加载/重新渲染吗?

它帮助我解决了问题。所以你必须使用这样的代码:

myTimer() {

  ... //Change text, e.g.: %, timer and so on. Check condition for halt.

  this.vueTextVar = newTextValue;
  this.$forceUpdate();
  setTimeout(() => {
          this.myTimer();
        }, 1000);
}
© www.soinside.com 2019 - 2024. All rights reserved.