如何在Vue属性中传递XMLHttpRequest responseText



我希望能够检索我的请求的响应并将其存储在属性中,但我无法在函数onretaystatchange中访问我的属性customerArray。

export default {
name: "CustomerList",
data() {
return {
customerArray: []
}
},
methods: {
retrieveAllCustomer: function () {
var xhr = new XMLHttpRequest();
var url = "https://url";
xhr.open("GET", url, false);
xhr.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
//Does not refer to customerArray
this.customerArray = JSON.parse(this.responseText);
} else {
console.log(this.status, this.statusText);
}
}
};
xhr.send();
}
}
}

是否可以在readystatechange中指向customerArray?

xhr.onreadystatechange = function ()导致this引用更改为XMLHttpRequest对象。因此,this.customerArray不再存在。为了避免这种情况,创建一个对原始this:的新引用

retrieveAllCustomer: function () {
var comp = this;
var xhr = new XMLHttpRequest();
var url = "https://url";
xhr.open("GET", url, false);
xhr.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
comp.customerArray = JSON.parse(this.responseText);
} else {
console.log(this.status, this.statusText);
}
}
};
xhr.send();
}

您的问题属于函数的范围,因为onreadystatechange之后的问题与以前不同。

使用() => { }而不是function () { }:

...
xhr.onreadystatechange = () => {
if (this.readyState === XMLHttpRequest.DONE) {
...

在这里你可以读到一个很好的解释。

最新更新