Reputation: 85
I have JSON output from server:
[
{"id":"2","name":"Peter","age":"24"},
{"id":"4","name":"Lucy","age":"18"},
]
and now I want to use it with v-for
directive, but it doesn't work for me.
Here is my export default:
data () {
return {
info: {}
}
},
mounted () {
axios
.get('http://localhost:4000/fetch.php/')
.then(response => (this.info = response.data))
},
And now if I want to display output of info, it works well {{ info }}
.
But I need to use v-for
directive and display only names.
<p v-if="info.name">{{ info.name }}</p>
But it is not working, only what is working is this: {{ info[0].name }}
.
Upvotes: 0
Views: 985
Reputation: 3620
You cannot read the name
property directly like this: info.name
. Since the output is an array of objects rather than a single object.
data () {
return {
info: [], // make this an empty array
}
},
mounted () {
axios
.get('http://localhost:4000/fetch.php/')
.then(response => (this.info = response.data))
},
Then, you can render the info
array in your template using v-for
directive:
<ul v-if="info.length">
<li v-for="item in info" :key="item.id">{{ item.name }}</li>
</ul>
Read more about List Rendering in Vue.
Upvotes: 2