vuejs中this代表什么含义

vuejs中this代表什么含义,第1张

vuejs中this代表什么含义

vuejs中this代表的含义:1、vue组件或者实例中,this代表调用它的Vue实例;2、回调函数中,this代表父级组件;3、箭头函数中,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代表什么含义的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/696991.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-22
下一篇 2022-04-22

发表评论

登录后才能评论

评论列表(0条)

保存