我正在尝试使用 Vue.js 将 JSON 有效负载中的对象列表解析为表。
我想从数组中的第一个对象中获取键来创建表标题,下面的代码可以工作并提供正确的值,但问题是我不断收到此错误消息
错误信息
[Vue warn]: Error in render function: "TypeError: objectArray is null"
(found in <Root>)
Html 元素
<thead>
<tr>
<th v-for="(value, key) in objectArray[0]">
{{ key }}
</th>
</tr>
</thead>
JSON 负载
[
{ "field1": "value", "field2": "value", "field3": "value", "field4": "value", "field5": "value", "field6": "value", "field7": "value" },
{ "field1": "value", "field2": "value", "field3": "value", "field4": "value", "field5": "value", "field6": "value", "field7": "value" },
{ "field1": "value", "field2": "value", "field3": "value", "field4": "value", "field5": "value", "field6": "value", "field7": "value" }
]
用于填充对象的 Vue 代码
var link = 'api/array';
new Vue ({
el: '#app',
data: {
objectArray: null
},
methods:{
getObjectArray: function(){
this.$http.get(link).then(function(response){
this.objectArray = response.data;
}, function(error){
console.log(error.statusText);
});
}
},
mounted: function () {
this.getObjectArray();
}
});
最佳答案
该错误是因为 objectArray 第一次为 null 并且不是数组。尝试使用此代码来防止错误,直到加载您的请求:
<thead v-if='objectArray'>
<tr>
<th v-for="(value, key) in objectArray[0]">
{{ key }}
</th>
</tr>
</thead>
关于javascript - Vue JS 使用 v-for 从对象数组获取 JSON 键值时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44934767/