Vikram Singh
Vikram Singh

Reputation: 124

Vue js. Data fields not binding

I have the following definition for the Vue element:

new Vue({
  el: "#app",
  data: {
    latitude1: 'a',
    name: 'aa'
  },
  mounted() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(position => {
        this.latitude1 = position.coords.latitude;
      })
    } else {
      this.latitude1 = "WTF??"
      // this doesn't work either:
      // this.$nextTick(() => { this.latitude1 = "WTF??" })
    }
  },
  methods: {
    // button works... WTF?!?
    doIt() {
      this.latitude1 = "WTF??"
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
  <div>{{ latitude1 }}: {{ name }}</div>
  <button @click="doIt">Do it</button>
</div>

I can see the location data being populated. The alert displays the latitude but the 2 way binding for the data field latitude1 is not working. I have tried storing the object state using this and that also did not work.

My html is as follows:

<div class="form-group" id="app">
 <p>
   {{latitude1}}
 </p>
</div>

Upvotes: 2

Views: 222

Answers (1)

Ehsan
Ehsan

Reputation: 1285

One of the things to do inside the Vue.js is to use the defined methods for reactive properties changes.

Here is a code I've provided for it:

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

new Vue({
  el: "#app",
  data: {
    latitude1: 'a',
    name: 'aa'
  },
  mounted: function() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(position => {
        console.log(position.coords.latitude);
        Vue.set(this, 'latitude1', position.coords.latitude);
      }, error, options)
    }
  }
});

I also set error handler and options for the navigator query. For following the results please check the console.

Upvotes: 3

Related Questions