【问题标题】:How to find nested key in the json object in vuejs如何在 vuejs 中的 json 对象中找到嵌套键
【发布时间】:2021-09-13 16:32:52
【问题描述】:

我正在尝试从我的 VUEjs 应用程序上的 Django API 获取的用户列表中显示用户。

来自 API 的我的用户列表数据:

{
  "count": 1,
  "next": null,
  "previous": null,
  "results": [
    {
      "url": "http://localhost:8000/v1/users/1/",
      "username": "admin",
      "email": "admin@example.com",
      "groups": []
    }
  ]
}

我的 VUE 代码:

<template>
    <div>
        <h1> Users </h1>
        <div v-for="results in APIData" :result="results" :key="results.username">
            <h5>{{ result.username }}</h5>
            <p>{{ result.email }}</p>
        </div>
    </div>
</template>

<script>
import { getAPI } from '../axios-api';
import { mapState } from 'vuex';

export default {
    name: 'Users',
    computed: mapState(['APIData']),
    created() {
        getAPI.get('/v1/users/', { headers: { Authorization: 'Bearer ' + this.$store.state.accessToken } })
        .then(response => {
            this.$store.state.APIData = response.data
        })
        .catch(error => {
            console.log(error)
        })
    }
}
</script>

由于某种原因,即使我可以看到我的 API 请求成功并且我可以在我的网络选项卡中看到数据,数据也没有显示在网页上。显示用户的方式是否正确?还是我错过了什么?

我是 VUEjs 的新手,有人可以帮忙吗?

【问题讨论】:

    标签: javascript vue.js vuex


    【解决方案1】:

    如果您只想在APIData 中通过results 循环:

    new Vue({
      el: '#demo',
        data() {
          return {
          APIData: {
            "count": 1,
            "next": null,
            "previous": null,
            "results": [
              {
                "url": "http://localhost:8000/v1/users/1/",
                "username": "admin",
                "email": "admin@example.com",
                "groups": []
              },
              {
                "url": "http://localhost:8000/v1/users/1/",
                "username": "user",
                "email": "user@example.com",
                "groups": []
              }
            ]
          }
        }
      },
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="demo">
      <template>
        <div>
          <h1> Users </h1>
          <div v-for="result in APIData.results" :key="result.username">
            <h5>{{ result.username }}</h5>
            <p>{{ result.email }}</p>
          </div>
        </div>
      </template>
    </div>

    【讨论】:

      【解决方案2】:

      问题出在 v-for 中,您可以尝试: v-for="results in APIData.results" 因为“results”不是访问器,是您分配给数组中每个值的名称,并且 APIData 不是数组。

      【讨论】:

      • 那我该怎么做呢?我应该写什么而不是当前状态?
      • 我看到这样的“v-for="result in APIData.results" :key="result.username"
      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 2014-07-25
      • 2017-12-24
      相关资源
      最近更新 更多