父向子异步传值子组件拿不到值的问题(以Echarts为例)

232 阅读1分钟

问题描述

父向子异步传值子组件拿不到值的问题

image.png

为了复用性将其封装成为单独的组件。在使用时,由于数据是请求来的,所以会导致加载出来后没有数据.

<template>
    <bar-chart :chartData="projectStatus"/>
</template>
data(){
    projectStatus:[]
},
created(){
    this.getBase();
}
method:{
  getBase(){
    getBarDate().then(res=>{
       if(res.code === 200){
           this.projectStatus = res.data;
           //在这里log的话是有数据的,但是由于视图先加载,数据后赋值。
           //所以刚开始传过去的chartDate是空的,但是等数据请求过来后chatDate是有数据的.
       }
    })
  }
}

解决办法

  • 使用v-if判断当有数据后在进行组件的加载
<bar-chart :chartData="projectStatus" v-if="projectStatus.length > 0"/>

这种办法可以很干脆的解决了问题,但是用户体验度不太好

  • 使用watch监听数据,当数据更新后重新给echarts赋值
    //barChart
    props:{
	chartData:{
            type:Array
          }
    }
     watch: {
        chartData(val) {
          this.chartData = val;
          this.getBase();
          this.$nextTick(() => {
            this.initChart();
          });
        }
      },