Way to find JSON objects of nested keys in Vue.js
P粉872182023
2023-08-30 09:44:36
<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>
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.If you just want to loop through the
results
inAPIData
: