如何在 Vue 属性中传递 XMLHttpRequest responseText

A. *_*dam 3 ajax xmlhttprequest vue.js

我希望能够检索我的请求的响应并将其存储在属性中,但我无法在函数 onreafystatchange 中访问我的属性 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();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

是否可以在 onreadystatechange 中指向 customerArray?

Sur*_*Man 5

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();
        }
Run Code Online (Sandbox Code Playgroud)