[Vuejs]-Vuejs not setting data property from arrow function

4👍

Here is an example of converting to a promise and using async/await:

async getCurrentLocation() {
    const position = await new Promise(resolve => {
        navigator.geolocation.getCurrentPosition(position => resolve(position))
    });

    this.currentLat = position.coords.latitude;
    this.currentLong = position.coords.longitude;

    console.log(this.currentLat); // shouldn't print initial value
},

1👍

Your code is valid, the callback arrow function is asynchronous (it’s not executed immediately) and the call of console.log(this.currentLat); is synchronous which makes it to be executed before the callback context, the property is properly if you use it inside the template it will work fine

0👍

Set the values in a callback as follows:

<template>
  <div id="app">{{ currentLat }} - {{ currentLong }}</div>
</template>

<script>
export default {
  data() {
    return {
      currentLat: "intial Lat",
      currentLong: "intial Long",
    };
  },
  mounted() {
    this.getCurrentLocation();
  },
  methods: {
    getCurrentLocation() {
      navigator.geolocation.getCurrentPosition(this.setCoordinates);
    },
    setCoordinates(position) {
      this.currentLat = position.coords.latitude;
      this.currentLong = position.coords.longitude;
    },
  },
};
</script>

Leave a comment