数据变量未从 VueJS 中的方法更新

Data variable not updating from method in VueJS

我正在使用以下代码从 HTML5 地理位置 API 获取访客邮政编码(pin 码)。但是,我想获取该邮政编码并将其更新为数据变量 'pincode'。下面是我使用的代码,值在控制台中正确打印。但未在 'pincode' 变量中更新。

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

这是因为您在 geocoder.geocode 函数

中丢失了 this 的上下文
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
       }
   }
});

这应该有效。

您可以使用 arrow function, which does not bind it's own this, arguments, super, or new.target 语法代替 function() 语法,如下所示:

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