从vueJS方法调用setTimeout()不起作用 [英] setTimeout() not working called from vueJS method

查看:608
本文介绍了从vueJS方法调用setTimeout()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试允许用户从应用中重置或关闭给定的服务器.我正在界面上工作,并希望向用户发送有关正在发生的事情的消息.我显示在数据对象中定义的消息,以指示已采取的措施.我可以使用setTimeout来切换一个reset ....消息和一个reset消息.请参阅以下方法.

I am trying to allow a user to reset or shutdown a given server from an app. Im working on the interface right now, and want to give the user messages as to what is happening. I display a message defined in my data object to indicate the action taken. I thene use setTimeout to switch a resetting.... message with a reset message. See the following method.

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

    } 

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

In my browser I can trigger this message and my message of "Resetting" displays, but the following "Reset" message is never output. Do I have any formatting errors?

将这种方法放在上下文中是我的整个组件.

To put this method in context here is my entire component.

  <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?  

推荐答案

setTimeout内的this值不同.

如果您使用的是ES6,则可以使用箭头功能:

If you're using ES6, you can use an arrow function:

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

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

Or if you're not, you can bind the value of this:

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

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

However, having never used Vue, I don't know if it will know to re-render when you change the value of this.message, or if you should be changing some component state or something.

这篇关于从vueJS方法调用setTimeout()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆