我有一个像这样的简单表格
<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中的methods对象中的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,然后使用它来填充表 出于测试目的,我刚刚尝试了这个
<span v-if="userData.length > 0">
some data
</span>
<span v-else>
data not found
</span>
console.log 显示 userData 已更新,但上面的这段代码没有改变。
最佳答案
您无法通过 then
函数中的 this
访问虚拟机。您可以通过三种方式解决此问题:
显式绑定(bind)外部
this
作为函数的执行上下文(ES5 函数有自己的 this):.then(function (response) { this.userData = response.data; console.log(this.userData); }.bind(this))
将
this
上下文存储在局部变量中,例如self
或that
: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); }); }
使用没有自己的
this
的 ES6 箭头函数:.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
关于javascript - 数据不会在 vue js 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48336284/