1

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?

2 Answers 2

1

Use an arrow function to preserve the context:

GoogleMapsLoader.load((google) => {
  var sv = new google.maps.StreetViewService();
  console.log(this.location);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Keep in mind, es6 arrow functions aren't supported in IE11, but if you are using the typical Vue/Webpack setup with Babel, it will be transpiled to work.
1

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

    });
}, 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.