首页 > 解决方案 > 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!!!

标签: javascriptvue.jsvuejs2vue-componentvuex

解决方案


问题是this在你的 ajax 返回函数内部不再引用 vue 实例。

解决方案是将this关键字保存到函数内部的变量中。例子:

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);
    },
  });
}

以下是有关关键字行为的更多信息thishttps ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this


推荐阅读