javascript - 无法读取未定义的属性变量。哪里有错?
问题描述
我试图从另一个站点获取数据并将其添加到数组中,然后我想在选择中使用数据,但出现错误:
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)
});
}
}
我的错误在哪里?怎么会是正确的?
解决方案
这似乎是this
问题的上下文。
在您getLocations()
尝试在以下内容之前添加此行fetch
:
let vm = this
然后在你的fetch
函数中使用:
vm.locationList.push(list);
代替this.locationList.push(list);
希望能帮助到你。祝你好运。
推荐阅读
- android - BubbleWrap CLI 显示错误 The given android-sdk is not correct when bubblewrap build
- javascript - 如何在mongodb中将集合A中的字符串与集合B匹配
- bash - 从文本文件中提取属性值
- google-cloud-storage - 我们可以使用单个 Google Cloud Dataflow 将来自多个 Pubsub(源)的数据写入多个 GCS(接收器)吗?
- wordpress - woocommerce 中的四舍五入价格
- c++ - 使用虚拟析构函数c ++删除指向基类的指针(*&)
- node.js - Nodejs - mongodb - 有没有一种简单的方法来获得分组/聚合结果?
- sql - 同时计算会话数
- matlab - 在 Matlab 中绘制 3d 数据
- c# - NAudio Asio 录制播放和保存(仅限噪音)