我正在尝试允许用户从应用程序重置或关闭给定服务器。我现在正在处理界面,并希望向用户提供有关正在发生的事情的消息。我显示在我的数据对象中定义的消息以指示所采取的操作。然后我使用 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?
最佳答案
this
的值在setTimeout
中是不同的。
如果你使用的是 ES6,你可以使用箭头函数:
setTimeout(() => { this.message = this.server + ': Reset' }, 2000)
或者如果你不是,你可以绑定(bind)this
的值:
setTimeout(function () {
this.message = this.server + ': Reset'
}.bind(this))
但是,由于从未使用过 Vue,我不知道当您更改 this.message
的值时它是否会知道重新渲染,或者您是否应该更改某些组件状态或一些东西。
关于javascript - 从 vueJS 方法调用的 setTimeout() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45301063/