我使用vuejs和axios进行简单的ajax调用:
var app1 = new Vue({
el: '#app1',
data: {
test: []
},
methods: {
setAJAX: function () {
axios.get('/Departments/GetDepartments/').then(response => this.test = response.data.listBACAET);
}
}
});
为什么这样做是有效的:
setAJAX: function () {
axios.get('/Departments/GetDepartments/').then(response => this.test = response.data.listBACAET);
}
但是这不起作用,更改不会映射到表中(this.test未定义):
setAJAX: function () {
axios.get('/Departments/GetDepartments/').then(function(response){this.test = response.data.listBACAET});
}
发布于 2019-11-25 10:07:09
这是因为箭头函数的工作方式:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this
当使用箭头函数时,this
被隐式绑定到封闭作用域的this
,在您的示例中,这是调用该方法的vue实例。因此,您正在设置视图模型的数据,这是可行的。
当使用性病的时候。函数,在作用域中没有this
,因此出现了错误。用性病。函数,您需要为视图模型定义一个闭包,如下所示:
setAJAX: function () {
let vm = this
axios.get('...').then( function(response) {
vm.test = response.data.listBACAET
});
}
https://stackoverflow.com/questions/59029220
复制相似问题