Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJs this.method is not a function? How to call a method inside another method in Vuejs?

I'm trying to call a method from another method and for this I've used this. But my console is causing me an error.

How to call a method inside another method in Vuejs?

code

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

console:

this.buscarLojas is not a function

like image 206
cura Avatar asked Jul 11 '18 15:07

cura


1 Answers

You have an anonymous call back function that overwrites this keyword, you can either assign this to another variable ref before using it in your anonymous function:

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

Or use an arrow function:

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)
    }
}
like image 197
Psidom Avatar answered Sep 17 '22 16:09

Psidom