首頁  >  文章  >  web前端  >  vuejs中this代表什麼意義

vuejs中this代表什麼意義

青灯夜游
青灯夜游原創
2021-10-26 15:38:5911391瀏覽

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