source

VueJ의 메서드에서 데이터 변수가 업데이트되지 않음s

bestscript 2022. 10. 22. 09:29

VueJ의 메서드에서 데이터 변수가 업데이트되지 않음s

HTML5 지오로케이션 API에서 방문자의 우편번호(핀코드)를 얻기 위해 아래와 같은 코드를 사용하고 있습니다.그러나 나는 그 우편번호를 취득하여 데이터 변수 '핀코드'로 업데이트하고 싶다.다음은 제가 사용한 코드입니다.값은 콘솔에 올바르게 인쇄됩니다.그러나 '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
                        }
                    }
                });
            });
        }    
    }
}

이것은, 다음의 콘텍스트를 잃었기 때문입니다.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
       }
   }
});

효과가 있을 거야

사용하는 대신function()구문은 다음과 같이 자체 this, 인수, super 또는 new.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
       }
   }
});

언급URL : https://stackoverflow.com/questions/41995304/data-variable-not-updating-from-method-in-vuejs