[Vuejs]-How to assign vue value to vue data variable to Vue.nexttick function?

0πŸ‘

i believe you’re experiencing a javascript scoping issue. try the following:

export default {

    /* ... */

    mounted(){

        let _this = this; // <---- keep Vue model in a variable.

        $("#geocomplete").bind("geocode:dragged", function (event, latLng) {

            // we're now inside an inner scope,
            // 'this' isn't Vue model anymore,
            // which is why we prepared '_this'.

            $("input[name=lat]").val(latLng.lat());
            $("input[name=lng]").val(latLng.lng());

            _this.lat = $("#lat").val();
            _this.lng = $("#lng").val();
            console.log("here" + _this.lat + "lng:" + _this.lng);
            $("#reset").show();
        });
    },

    /* ... */

}

hope that helps.

0πŸ‘

The reason is as geevee explained, and besides using a variable to store the Vue this, you can also use arrow functions as Satyam Pathak metioned:

mounted () {
  this.$nextTick(function () {
    // Use arrow functions in the callback
    $('#geocomplete').on('geocode:dragged', (event, latLng) => {
      $('input[name=lat]').val(latLng.lat());
      $('input[name=lng]').val(latLng.lng());
      this.lat = $('#lat').val();
      this.lng = $('#lng').val();
      console.log('here lat: ' + this.lat + ' lng: ' + this.lng);
      $("#reset").show();
    })
  });
}

Explanation and examples of arrow functions on MDN

β€œAn arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope.β€œ

A simulated sample can be referred on CodePen

Leave a comment