Watch monitoring, solve the problem that the Vue3 parent component asynchronous props passes the value, and the child component cannot receive the problem

When writing static data, it is no problem for the parent component to pass the value to the child component to receive and render, but when the parent component obtains the data asynchronously, the child component will receive the data later than the rendering, and there will be a problem of not being able to receive it. I am using echarts to draw When the chart is displayed, the chart will not be displayed directly

 Use watch to monitor props data and perform assignment operation in watch to solve this problem

directly on the code

Parent component, vue3 syntax

setup() {
            // 用定时器模拟发请求异步获取后端接口的数据
            const weekNumber = ref([])
            setTimeout(()=>{
                weekNumber.value=[150, 120, 200, 80, 170, 110, 130]
                console.log( weekNumber.value[0]);//值为150,后打印
            },1000)
            console.log( weekNumber.value[0]);//值为undefined,先打印
            return{ weekNumber};
        }

Subcomponent props are normally received, but the received data should be listened in the watch

watch(()=>props.weekNumber,(newVal) => {
        console.log("newVal:",newVal);
        info.options.series[0].data =newVal
        initChart()//重绘echarts图表
        console.log("weekNumber在watch之后:",props.weekNumber);//后打印,接收到新数据
      })
      console.log("weekNumber在watch之前:",props.weekNumber);//先打印,接收不到
    

Take a look at the console print order

 

Guess you like

Origin blog.csdn.net/weixin_46764819/article/details/128311949
Recommended