VueJs this.method不是函数吗?如何在Vuejs中的另一个方法内调用一个方法?

cur*_*ura 2 google-maps-api-3 vue.js

我试图从另一个方法中调用一个方法,为此,我使用了它。但是我的控制台导致我出错。

如何在Vuejs中的另一个方法内调用一个方法?

 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)
     }
 }
Run Code Online (Sandbox Code Playgroud)

安慰:

this.buscarLojas不是函数

Psi*_*dom 8

您有一个覆盖this关键字的匿名回调函数,可以在匿名函数中使用它之前将其分配this给另一个变量ref

methods: {
    searchLocations: function () {
      var address = this.search
      var geocoder = new window.google.maps.Geocoder()
      var ref = this
//    ^^^^^^^^^^^^^^
      geocoder.geocode({address: address}, function (results, status) {
        if (status === window.google.maps.GeocoderStatus.OK) {
          ref.buscarLojas(results[0].geometry.location)
        //^^^
        } else {
          alert(address + ' not found')
        }
      })
    },
    buscarLojas: function (center) {
      console.log(center)
    }
}
Run Code Online (Sandbox Code Playgroud)

或使用箭头功能:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 第二种选择更好 (2认同)