vuejs中this代表什么含义
时间:2022-02-11 17:46
vuejs中this代表的含义:1、vue组件或者实例中,this代表调用它的Vue实例;2、回调函数中,this代表父级组件;3、箭头函数中,this代表定义它时所处的对象,即宿主对象。 本教程操作环境:windows7系统、vue2.9.6版,DELL G3电脑。 1 vue组件中 在 2 回调函数 此时回调函数 3 箭头函数 相关推荐:《vue.js教程》 以上就是vuejs中this代表什么含义的详细内容,更多请关注gxlsystem.com其它相关文章!Vuejs中的this变量
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
实例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
会报错找不到函数箭头函数
没有自己的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
组件