Как передать ответный текст XMLHttpRequest в свойствах Vue - PullRequest
0 голосов
/ 28 ноября 2018

Я хотел бы получить ответ на мой запрос и сохранить его в свойстве, но не могу связаться с моим свойством customerArray в функции onreafystatchange.

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();
            }
        }
    }

Можно ли указать на массив клиентов в onreadystatechange?

Ответы [ 2 ]

0 голосов
/ 28 ноября 2018

Ваша проблема связана с областью действия внутри функции, поскольку после onreadystatechange она уже не такая, как раньше.

Используйте () => { } вместо function () { }:

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

Здесь вы можете прочитать хорошее объяснение по этому поводу.

0 голосов
/ 28 ноября 2018

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();
        }
...