[英]How do I access a property of each JSON object?
所以我正在使用 Axios 進行 API 調用,並將 JSON 響應推送到一個空數組。 我在訪問每個對象的各個屬性時遇到問題。 `
<div class="wrapper">
<div class="row">
<div v-for="group in groups" :key="group.id">
<div class="col-md-4 cards">
<h3>{{ group[1].name }}</h3>
<h3>{{ group.name }}</h3>
</div>
</div>
</div>
</div>
</div>
然后我的js是
import axios from 'axios'
export default {
name: 'app',
data () {
return {
groups: [],
loading: false
}
},
methods: {
getHomes: function() {
this.loading = true;
axios.get("*******")
.then((response) =>{
this.loading = false;
this.groups.push(response.data);
// console.log(this.groups)
}, (error) => {
this.loading = false;
})
},
我可以通過對數組索引進行硬編碼來訪問每個單獨的 group.name,但是我在動態訪問它們時遇到了問題。
而不是這樣做:
.then((response) =>{
this.loading = false;
this.groups.push(response.data);
}, (error) => {
this.loading = false;
})
只需將 response.data 分配給 groups 變量。
.then((response) =>{
this.loading = false;
this.groups = response.data;
}, (error) => {
this.loading = false;
})
在你的模板中:
<div v-for="(group, index) in groups" :key="index">
<div class="col-md-4 cards">
<h3>{{ group.name }}</h3>
<h4>{{ group.url }}</h4>
</div>
</div>
您無法訪問該項目的原因是因為您將對象數組推送到數組中,因此您需要遍歷另一個數組中的數組。
在您的示例數據集中,您在 Axios 調用中獲得的response.data
似乎已經是一個數組。 你應該這樣做。
"use strict";
import Vue from "vue";
import Axios from "axios";
export default Vue.component({
data() {
return {
groups: [],
loading: false
};
},
created() {
this.loading = true;
axios.get("https://somwhere.com/api/something").then(response => {
this.groups = response.data;
}).finally(() => this.loading = false);
}
});
此外,您應該在finally
塊中取消加載。 我主動添加了它,以便您可以看到它是如何完成的,即使它超出了問題的范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.