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

Gij*_*ese 3 javascript vue.js vue-component vuejs2

我正在使用以下代码从HTML5地理位置API获取访问者邮政编码(密码).但是,我想获取该邮政编码并将其更新为数据变量'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
                        }
                    }
                });
            });
        }    
    }
}
Run Code Online (Sandbox Code Playgroud)

Amr*_*pal 10

这是因为你丢失了函数this内部的上下文geocoder.geocode

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
       }
   }
});
Run Code Online (Sandbox Code Playgroud)

这应该工作.


Sau*_*abh 5

除了使用function()语法,您还可以使用arrow函数,该函数不绑定它自己的thisargumentssupernew.target,如下所示:

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
       }
   }
});
Run Code Online (Sandbox Code Playgroud)