Gijo Varghese Gijo Varghese - 4 years ago 214
Javascript Question

Data variable not updating from method in VueJS

I'm using the following code to get visitors zip code(pin code) from HTML5 geolocation API. However, I want to get that zip code and update it to a data variable 'pincode'. Below is the code I used, the value prints in console correctly. But not updating in 'pincode' variable.

export default {
data(){
return {
pincode: 0,
}
},
methods: {
findPincode(){
navigator.geolocation.getCurrentPosition(function (position) {
var geocoder = new google.maps.Geocoder();
var latLng = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
geocoder.geocode({
'latLng': latLng
}, function (results, status) {
for (var i = 0; i < results[0].address_components.length; i++) {
var address = results[0].address_components[i];
if (address.types[0] == "postal_code") {
console.log(address.long_name) // prints 680001
this.pincode = Number(address.long_name) // not working
}
}
});
});
}
}
}

Answer Source

This is because you lost the context to this inside your geocoder.geocode function

let self = this
geocoder.geocode({
   'latLng': latLng
}, function (results, status) {
    for (var i = 0; i < results[0].address_components.length; i++) {
       var address = results[0].address_components[i];
       if (address.types[0] == "postal_code") {
          console.log(address.long_name) // prints 680001
          self.pincode = Number(address.long_name) // not working
       }
   }
});

and that should work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download