原文地址:https://www.jianshu.com/p/50afd1b5ddf6
为了避免this指向出现歧义,有两种方法绑定this。
使用bind
showMessage1()可以改为:
showMessage1:function(){
setTimeout(function() {
document.getElementById("id1").innerText = this.message; //this 3
}.bind(this), 10)
}
对setTimeout()里的匿名函数使用bind()绑定到vue实例的this。这样在匿名函数内的this也为vue实例。
把vue实例的this赋值给另一个变量再使用
showMessage1()也可以改为
showMessage1:function(){
var self = this;
setTimeout(function() {
document.getElementById("id1").innerText = self.message; //改为self
}.bind(this), 10
}