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

时间:2021-04-25 22:42:19

标签: javascript vue.js vuejs2 axios vuejs3

使用 VueJS 和 Axios,如何检索 API 数据并将其传递给多个子组件?我想通过 props 检索和传递这些数据,这样我就不必通过子组件多次访问 API。

目前,子组件返回“未定义”。

父母

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

儿童

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

1 个答案:

答案 0 :(得分:1)

v-if=(及其对应的 v-else)根据 js 表达式的真值有条件地控制 DOM 中的内容。您可以使用计算结果为 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>