Skip to content
Advertisement

How to save data in Vue instance

The question is quite simple, All I want is to get the data after the AJAX post saved in Vue instace’s data. Here is my code:

const VMList  = new Vue({
  el: '#MODAL_USER_DATA',
  data: {
    user: []//,
    //userAcc: []
  },
  methods: {
    getUserAcc: function ( userID ) {

      this.user = { _id : userID };

      var self = this
      $.ajax({
        url: "/listuser",
        type: "POST",
        data: this.user,
        success: function(data) {
          this.user = data ;
          //this.userAcc = Object.assign({}, this.userAcc, data );
          alert(JSON.stringify(this.user));//show the user correctly (e.g user = data)
          $('#popupDeleteModal').modal('show');
          alert(JSON.stringify(data));//show data,the entire json object,everything is good
        },
        error: function(err) {
          console.log('error: ',err);
        },
      });

    }
  }
});

And after I trigger the getUserAcc(id) method,I try to verify the VMList.user value in browser console,and I get only the id.Seems like after the function is over the data is reset.How could I store the data from the AJAX post request in the user object from data:{…} ?

Thank you for help!!!

Advertisement

Answer

The problem is that this inside your ajax return function doesn’t refer to the vue instance anymore.

The solution is to save the this keyword into a variable inside the function. Example:

getUserAcc: function ( userID ) {
  var that = this;
  this.user = { _id : userID };
  $.ajax({
    url: "/listuser",
    type: "POST",
    data: this.user,
    success: function(data) {
      that.user = data;
      //Rest of your code
    },
    error: function(err) {
      console.log('error: ',err);
    },
  });
}

Here is more information about the behavior of the keyword this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement