简体   繁体   English

VueJS - 如何将 Axios 响应数据从父组件传递到子组件?

[英]VueJS - How to pass Axios response data from parent to child component?

Using VueJS & Axios, how do I retrieve API data and pass it to multiple child components?使用 VueJS & Axios,我如何检索 API 数据并将其传递给多个子组件? I want to retrieve and pass this data through props so I will not have to access the API multiple times via the child components.我想通过道具检索和传递这些数据,这样我就不必通过子组件多次访问 API。

Currently, child component is returning 'undefined'.目前,子组件正在返回“未定义”。

Parent家长

<template>
    ...
    <my-child :foo="bar" />
    ...
    <my-other-child :foo="bar" />
    ...
</template>
<script>
    import axios from 'axios'
    ...
    mounted(){
        axios.get(...)
             .then(rsp => {this.bar = rsp.data.result})
             .catch(err => {console.warn(err)})
    }
    ...
</script>

Child孩子

<script>
    props: ['foo'],
    mounted(){
        console.log(this.foo)
    }
</script>

v-if= (and its counterpart, v-else ) control what's in the DOM conditionally based on the truth value of a js expression. v-if= (及其对应物v-else )根据 js 表达式的真值有条件地控制 DOM 中的内容。 You can keep any node out of the dom (including your my-child components) by qualifying it with a v-if that evaluates to false.您可以通过使用评估为 false 的 v-if 来限定任何节点(包括您的my-child组件),将其保留在 dom 之外。

 var app = new Vue({ el: '#app', data: { bar: null }, mounted () { setTimeout(() => this.bar = 'foo', 2500); } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <div> <div v-if="bar">bar is {{bar}}</div> <div v-else>bar is not initialized</div> </div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM