0

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 }}.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.