儿童作为道具收到的数据为空

时间:2020-04-08 09:44:56

标签: vue.js d3.js

我正在从父级调用json并将结果数据作为道具发送给子级。 但是在子数据中,数据为零。

parent.vue

<template>
  <subscriberGraph :propSubData="subData" /> // child component
</template>
<script>
data() {
    return {
      subData: [] // subData declaration
    };
},
methods: {
    async getSubscribers() {
      this.subData = await d3.json("./data/subscribers.json"); // calling json
      console.log("1: ", this.subData); // variable is declared in this file and data is getting displayed here, 
    }
  },
  mounted() {
    this.getSubscribers();
  }
 </script>

下面是子组件。

subscriberGraph.vue

<script>    
export default {
  mounted() {
    console.log("2: ", this.propSubData); // data length: 0 
  }
 props: ["propSubData"]
</script>

编辑:subData已经声明,这就是我在console.log(“ 1” ...)旁边的注释中提到的内容。无论如何都更新上面的代码,请检查。

2 个答案:

答案 0 :(得分:0)

您必须在subData部分中初始化data才能使用它。由于从请求中获取响应会花费一些时间,因此可以在子组件正在调用时使用v-if条件。这样可以防止在设置响应之前呈现子组件。

<template>
  <subscriberGraph :propSubData="subData" v-if="subData && subData.length>0" /> // child component
</template>
<script>
export default {
  data:()=>{
    return {
      subData:null
    }
  },
  methods: {
    async getSubscribers() {
      this.subData = await d3.json("./data/subscribers.json"); // calling json
      console.log("1: ", this.subData); // variable is declared in this file and data is getting displayed here, 
    }
  },
  mounted() {
    this.getSubscribers();
  }
}

答案 1 :(得分:0)

添加手表{}解决了该问题。
subscriberGraph.vue

 <script>    
     export default {
      methods: {
        drawBarGraph(data) {
          console.log("3: ", data); // working now !!
        }
      },
      mounted() {
        this.drawBarGraph(this.propSubData);
      },
      props: ["propSubData"],
      watch: {
        propSubData: function(newData) {
          this.drawBarGraph(newData);
        }
      }
    </script>

您需要监视更改,最初您不会获得数据,因为子组件在安装时尚未收到数据。稍后,当接收到数据时,watch {}观察并更新数据,因此数据现在在drawBarGraph()中可用。