【问题标题】:How to save data in Vue instance如何在 Vue 实例中保存数据
【发布时间】:2023-03-07 03:46:02
【问题描述】:

这个问题很简单, 我想要的只是在 Vue instace 的数据中保存 AJAX 帖子后获取数据。 这是我的代码:

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

    }
  }
});

在我触发getUserAcc(id)方法后,我尝试在浏览器控制台中验证VMList.user值,我只得到了id。好像函数结束后数据被重置了。我该如何存储来自 data:{...} 的用户对象中的 AJAX 发布请求中的数据?

谢谢你的帮助!!!

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vuex


    【解决方案1】:

    问题是您的 ajax 返回函数中的 this 不再引用 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);
        },
      });
    }
    

    这里有更多关于关键字this行为的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-15
      • 1970-01-01
      • 2019-03-28
      • 2017-11-29
      • 2021-01-13
      • 2020-01-29
      • 1970-01-01
      相关资源
      最近更新 更多