首页 > 解决方案 > 无法读取未定义的属性变量。哪里有错?

问题描述

我试图从另一个站点获取数据并将其添加到数组中,然后我想在选择中使用数据,但出现错误:

TypeError:无法读取未定义的属性“locationList”

data() {
    return {
        locationList: [{
            text: 'Default',
            value: 'none'
        }]
    }
}

我在 Created 上运行函数

created() {
    this.getLocations()
}

通过 fetch 从另一个站点获取数据的简单函数

methods: {
    getLocations: function() {
        fetch('https://www.webpagetest.org/getLocations.php?f=json')
            .then(function(response) {
                if (response.status === 200) {
                    return response.json()
                } else {
                    throw response;
                }
            })
            .then(function(data) {
                var list = Object.entries(data.data).map(([k, v]) => ({
                    text: v.Label,
                    value: k
                }))
                this.locationList.push(list);
            })
            .catch(function(e) {
                console.log(e)
            });
    }
}

我的错误在哪里?怎么会是正确的?

标签: javascriptvue.js

解决方案


这似乎是this问题的上下文。

在您getLocations()尝试在以下内容之前添加此行fetch

let vm = this

然后在你的fetch函数中使用:

vm.locationList.push(list);代替this.locationList.push(list);

希望能帮助到你。祝你好运。


推荐阅读