简体   繁体   中英

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

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.

Instead of using function() syntax, you can use arrow function , which does not bind it's own this , arguments , super , or new.target ., like following:

geocoder.geocode({
   'latLng': latLng
}, (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
       }
   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM