vuejs中this代表的含义是什么
本篇内容主要讲解"vuejs中this代表的含义是什么",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"vuejs中this代表的含义是什么"吧!
vuejs中this代表的含义:1、vue组件或者实例中,this代表调用它的Vue实例;2、回调函数中,this代表父级组件;3、箭头函数中,this代表定义它时所处的对象,即宿主对象。

本教程操作环境:windows7系统、vue2.9.6版,DELL G3电脑。
Vuejs中的this变量
1 vue组件中
在Vue所有的生命周期钩子方法(如beforeCreate,created,beforeMount,mounted,beforeUpdate, updated,beforeDestroy以及destroyed)里使用this,this指代调用它的Vue实例,即(new Vue)
new Vue({ data: { a: 1 }, created: function () { console.log('a is: ' + this.a) } methods: { plus: function () { this.a++ } }});vue组件或者实例中,不管是生命周期钩子函数created还是自定义函数plus,他们中的this都是指当前vue实例
2 回调函数
methods: { searchLocations: function() { var address = this.search var geocoder = new window.google.maps.Geocoder() geocoder.geocode({ address: address }, function(results, status) { if (status === window.google.maps.GeocoderStatus.OK) { this.buscarLojas(results[0].geometry.location) } }) }, buscarLojas: function(center) { console.log(center) } }此时回调函数function(results, status)会重新将this指向匿名对象(类比java匿名类),所以其中的this指代父级组件,执行this.buscarLojas会报错找不到函数
3 箭头函数
箭头函数没有自己的this,它的this是继承而来;默认指向在定义它时所处的对象(宿主对象),而不是执行时的对象
methods: { searchLocations: function () { var address = this.search var geocoder = new window.google.maps.Geocoder() geocoder.geocode({address: address}, (results, status) => { if (status === window.google.maps.GeocoderStatus.OK) { this.buscarLojas(results[0].geometry.location) } else { alert(address + ' not found') } }) }, buscarLojas: function (center) { console.log(center) }, group1:()=>{ //ES6的箭头函数写法,箭头函数没有自己的this,它的this事继承来的,指向在定义它时所处的宿主对象,在这里this指向window。 this....... },}箭头函数被绑定到父级上下文,因此其中的this会指向父级组件,针对情况三中的问题,将回调函数中的function改成箭头函数,会将this从匿名对象重新指向外部的vue组件
到此,相信大家对"vuejs中this代表的含义是什么"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!