因此,我正在使用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,但是我在动态访问它们时遇到了问题。

这是回应的图片
javascript - 如何访问每个JSON对象的属性?-LMLPHP

最佳答案

而不是这样做:

.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>


之所以无法访问该项目,是因为您正在将对象数组推入一个数组内,因此需要遍历另一个数组内的数组。

09-27 03:51
查看更多