Vue实例里this的使用

Vue实例里this的使用

这是vue文档里的原话:

All lifecycle hooks are called with their ‘this’ context pointing to the Vue instance invoking it.

意思是:在Vue所有的生命周期钩子方法(如created,mounted, updated以及destroyed)里使用this,this指向调用它的Vue实例
在这里插入图片描述
第一个输出英文"Hello!”,第二个输出中文“你好!”。
这说明了showMessage1()里的this指的是window,而showMessage2()里的this指的是vue实例。
created

created: function() {
  this.showMessage1();    //this 1
  this.showMessage2();   //this 2
}

created函数为vue实例的钩子方法,它里面使用的this指的是vue实例。

showMessage1()

showMessage1:function(){
    setTimeout(function() {
       document.getElementById("id1").innerText = this.message;  //this 3
    }, 10)
}

对于普通函数(包括匿名函数),this指的是直接的调用者
在非严格模式下,如果没有直接调用者,this指的是window。
showMessage1()里setTimeout使用了匿名函数,this指向window。

showMessage2()

showMessage2:function() {
    setTimeout(() => {
       document.getElementById("id2").innerText = this.message;  //this 4
    }, 10)
}

箭头函数是没有自己的this,在它内部使用的this是由它定义的宿主对象决定。showMessage2()里定义的箭头函数宿主对象为vue实例,所以它里面使用的this指向vue实例。
在这里插入图片描述

参考:https://majing.io/posts/10000005341170

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值