kevinunger
kevinunger

Reputation: 381

Vuejs - Cannot read property 'location' of undefined when loading API

I'm having problems accessing values of my data objects in Vue, after loading the Google maps-api.

Data:

data() {
    return {
        lat : 0,
        long : 0,
        location: '46.414382,10.013988' 
    }
}

My method, that I call.

methods: {
    randomLocation: function(){
        this.lat = Math.random() * (90 + 90) - 90;
        this.long = Math.random() * (180 + 180) - 180;
        this.location = this.lat + ',' + this.long;
        console.log("Random location: ", this.location);

        GoogleMapsLoader.load(
            function(google) {
                var sv = new google.maps.StreetViewService();
                console.log(this.location);
            }
        );
    }
}             

The console prints an error when I call randomLocation. It says it can't access this.location int GoogleMapsLoader.load(...). Why is that and how can I fix it?

Upvotes: 1

Views: 325

Answers (2)

Dan
Dan

Reputation: 63059

Use an arrow function to preserve the context:

GoogleMapsLoader.load((google) => {
  var sv = new google.maps.StreetViewService();
  console.log(this.location);
});

Upvotes: 1

Mitya
Mitya

Reputation: 34556

Because GoogleMapsLoader.load() runs in a context that is different from the context outside of it.

In other words, it changes what this points to. You can just cache a reference to the outer this:

randomLocation: function(){
    this.lat = Math.random() * (90 + 90) - 90;
    this.long = Math.random() * (180 + 180) - 180;
    this.location = this.lat + ',' + this.long;
    console.log("Random location: ", this.location);
    let outer_this = this; //<-- here

    GoogleMapsLoader.load(
        function(google)  {
        var sv = new google.maps.StreetViewService();
        console.log(outer_this.location); //<-- here

    });
}, 

Upvotes: 1

Related Questions