数据不会在 vue js 中更新

data does not update in vue js

我有一个像这样的简单表格

<form @submit.prevent="getSummary">
    <input type="text" v-model="userAcccount" placeholder="Enter Account 
    Number">
    <button type="submit" class="btn btn-xs btn-default">Submit</button>
</form>

而我的vue方法对象中的getSummary方法是这样的

methods: {
        getSummary () {               
            axios.get('core/handle.php', {
                params: {
                  accountNumber: this.userAcccount
                }
              })
              .then(function (response) {
                this.userData = response.data;
                console.log(this.userData);
              })
              .catch(function (error) {
                alert(error);
            });
        }
    }

我的数据对象包含

data: {
        userAcccount: '',
        userData: []
    },

我正在尝试使用 axios 的响应更新 userData,然后使用它来填充 table 出于测试目的,我刚刚尝试了这个

<span v-if="userData.length > 0">
      some data 
</span>
<span v-else>
      data not found
</span>

console.log 显示用户数据已更新,但上面的这段代码没有改变。

保存 this 的上下文,您就可以开始了。

methods: {
        getSummary () {
           var this_= this;
            axios.get('core/handle.php', {
                params: {
                  accountNumber: this_.userAcccount
                }
              })
              .then(function (response) {
                this_.userData = response.data;
                console.log(this_.userData);
              })
              .catch(function (error) {
                alert(error);
            });
        }
    }

如果这不起作用,请在 this_.userData = response.data 之后将 this_.$forceUpdate(); 添加到您的响应函数中,它将始终有效 ;)

您无法通过 then 函数中的 this 访问虚拟机。您可以通过三种方式解决此问题:

  1. 显式绑定外部 this 作为函数的执行上下文(ES5 函数有自己的 this):

    .then(function (response) {
        this.userData = response.data; 
        console.log(this.userData);
    }.bind(this))
    
  2. this 上下文存储在局部变量中,例如selfthat:

    getSummary () {
      const self = this;
      axios.get('core/handle.php', {
        params: {
          accountNumber: this_.userAcccount
        }
      })
      .then(function (response) {
        self.userData = response.data;
        console.log(self.userData);
      })
      .catch(function (error) {
        alert(error);
      });
    }
    
  3. 使用没有自己的ES6箭头函数this:

    .then(response => {
      this.userData = response.data;
      console.log(this.userData);
    })
    

Javascript 中 this 的概念与许多其他编程语言有很大不同,因为它描述了函数的执行上下文。这不是一个容易掌握的概念,但这帮助我进入了它:

http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

作为参考,MDN 始终是一个不错的去处:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

使用 ES6 箭头函数,您可以通过稍微重写来访问回调中的响应,如下所示:

.then(response => {
    this.userData = response.data;
    console.log(this.userData);
})

这是因为您当前正在使用 this 访问 axios 请求上下文,这显然是 null,因为 userData 不在您的范围内。通过使用箭头函数语法,您可以访问 userData 所在的父组件。