在Vue.js中查找嵌套键的JSON对象的方法
P粉872182023
P粉872182023 2023-08-30 09:44:36
[Vue.js讨论组]
<p>我正在尝试在我的VUEjs应用程序上显示来自Django API的用户列表中的用户。</p> <p>我的API中的用户列表数据:</p> <pre class="brush:php;toolbar:false;">{ &quot;count&quot;: 1, &quot;next&quot;: null, &quot;previous&quot;: null, &quot;results&quot;: [ { &quot;url&quot;: &quot;http://localhost:8000/v1/users/1/&quot;, &quot;username&quot;: &quot;admin&quot;, &quot;email&quot;: &quot;admin@example.com&quot;, &quot;groups&quot;: [] } ] }</pre> <p>我的VUE代码:</p> <pre class="brush:php;toolbar:false;">&lt;template&gt; &lt;div&gt; &lt;h1&gt; Users &lt;/h1&gt; &lt;div v-for=&quot;results in APIData&quot; :result=&quot;results&quot; :key=&quot;results.username&quot;&gt; &lt;h5&gt;{{ result.username }}&lt;/h5&gt; &lt;p&gt;{{ result.email }}&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; 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 =&gt; { this.$store.state.APIData = response.data }) .catch(error =&gt; { console.log(error) }) } } &lt;/script&gt;</pre> <p>由于某种原因,尽管我可以看到我的API请求成功并且在网络选项卡中可以看到数据,但数据没有显示在网页上。显示用户的方式正确吗?还是我漏掉了什么?</p> <p>我对VUEjs还不熟悉,有人可以帮忙吗?</p>
P粉872182023
P粉872182023

全部回复(2)
P粉145543872

问题出在v-for上,你可以尝试使用:v-for="results in APIData.results",因为"results"不是一个访问器,而是你给数组中的每个值分配的名称,而APIData不是一个数组。

P粉481815897

如果你只想循环遍历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>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号