Vue.js:从api获取数据并将其传递给child组件(简单示例)

Vue.js: Getting data from the api and passing it to a child component (simple example)

我想在 parent 组件上使用 axios 包发出 ajax 请求,并将返回的数组传递给 child 组件,以便它可以迭代数组并构建布局。我有以下代码。

parent是这样的:

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

child是这样的:

  <script>

export default {
name: "box",
props: ['mensagens']

 }

 </script>
  <template>
   <div>
 <div v-for="message in messages" > 
  {{ message}}
  </div>
  </div>

   </template>

   <style>
  </style>

在您的 parent 中,无需将 messages 声明为道具,它是您传递给 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});
       }
    }

在模板中,需要绑定属性.

    <box v-bind:messages="messages"></box>

    <box :messages="messages"></box>

child 需要将 messages 声明为 属性。

    export default {
      name: "box",
      props: ['messages']
    }