'Vue.js: Getting data from the api and passing it to a child component (simple example)
I want to make an ajax request using axios package on the parent component and pass the returned array to a child component so that it can iterate the array and build the layout. I have the following code.
The parent is this:
<script>
import Box from './Box';
import axios from 'axios';
export default {
name : "messagespainel",
data: function() {
return {messsages: []} //should I use data to pass the ajax returned array to the child
},
props: ['messages'] //should I use props to pass the ajax returned array to the child
}
mounted :
{
axios.get('http://www.omdbapi.com/?s=star&apikey=mykey').then(response => { this.messsages = response.data.Search});
}
</script>
<template>
<div>
<box messages="this.messages"></box> My mind bugs at this point. How to refer to messages?
</div>
</template>
The child is this:
<script>
export default {
name: "box",
props: ['mensagens']
}
</script>
<template>
<div>
<div v-for="message in messages" >
{{ message}}
</div>
</div>
</template>
<style>
</style>
Solution 1:[1]
In your parent, there is no need to declare messages
as a prop, it's a data property you are passing to the child.
import Box from './Box';
import axios from 'axios';
export default {
name : "messagespainel",
data: function() {
return {messages: []}
},
mounted() {
axios.get('http://www.omdbapi.com/?s=star&apikey=mykey')
.then(response => { this.messages = response.data.Search});
}
}
In the template, you need to bind the property.
<box v-bind:messages="messages"></box>
or
<box :messages="messages"></box>
The child needs to declare messages
as a property.
export default {
name: "box",
props: ['messages']
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | David Wolf |