首页  >  文章  >  web前端  >  vuejs中this代表什么含义

vuejs中this代表什么含义

青灯夜游
青灯夜游原创
2021-10-26 15:38:5911389浏览

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

vuejs中this代表什么含义

本教程操作环境:windows7系统、vue2.9.6版,DELL G3电脑。

Vuejs中的this变量

1 vue组件中

Vue所有的生命周期钩子方法(如beforeCreatecreatedbeforeMountmountedbeforeUpdateupdatedbeforeDestroy以及destroyed)里使用thisthis指代调用它的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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn