vuejs中this代表的含义:1、vue组件或者实例中,this代表调用它的Vue实例;2、回调函数中,this代表父级组件;3、箭头函数中,this代表定义它时所处的对象,即宿主对象。

本教程操作环境:windows7系统、vue2.9.6版,DELL G3电脑。
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组件
相关推荐:《vue.js教程》
以上就是vuejs中this代表什么含义的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号