search

Home  >  Q&A  >  body text

Way to find JSON objects of nested keys in Vue.js

<p>I'm trying to display users from a user list from Django API on my VUEjs application. </p> <p>User list data in my API:</p> <pre class="brush:php;toolbar:false;">{ "count": 1, "next": null, "previous": null, "results": [ { "url": "http://localhost:8000/v1/users/1/", "username": "admin", "email": "admin@example.com", "groups": [] } ] }</pre> <p>My VUE code:</p> <pre class="brush:php;toolbar:false;"><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></pre> <p>For some reason, although I can see that my API request is successful and the data is visible in the network tab, the data is not showing up on the web page. Is the way the user is displayed correct? Or am I missing something? </p> <p>I'm new to VUEjs, can anyone help? </p>
P粉872182023P粉872182023459 days ago483

reply all(2)I'll reply

  • P粉145543872

    P粉1455438722023-08-31 00:57:07

    The problem is with v-for, you can try to use: v-for="results in APIData.results", because "results" is not an accessor, but the value you give in the array Each value is assigned a name, and APIData is not an array.

    reply
    0
  • P粉481815897

    P粉4818158972023-08-31 00:28:43

    If you just want to loop through the results in APIData:

    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>

    reply
    0
  • Cancelreply