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

时间:2018-07-11 15:38:58

标签: 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)
     }
 }

控制台:

  

this.buscarLojas不是函数

3 个答案:

答案 0 :(得分:4)

您有一个覆盖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)
    }
}

或使用箭头功能:

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)
    }
}

答案 1 :(得分:0)

使用箭头函数进行回调

geocoder.geocode({address: address}, (results, status) => {
    if (status === window.google.maps.GeocoderStatus.OK) {
        this.buscarLojas(results[0].geometry.location)
    }
})

答案 2 :(得分:0)

我知道这里已经有答案了,但这也可以是一个方便的选择

methods: {
 var self = this;   //this line will take control of **this** which can be use later
 searchLocations: function() {
     var address = self.search
     var geocoder = new window.google.maps.Geocoder()
     geocoder.geocode({
         address: address
     }, function(results, status) {
         if (status === window.google.maps.GeocoderStatus.OK) {
             self.buscarLojas(results[0].geometry.location)
         }
     })
 },
 buscarLojas: function(center) {
     console.log(center)
 }

}