Vue3父组件使用props传值给子组件重新绘制echarts图表

目前网上实现这个小需求的大都是vue2的写法,更新一个vue3的写法,用了setup函数

父组件传值还是正常传

 子组件代码,vue3+setup

<template>
    <div class="echarts_class">
      
      <div id="bar" :style="{  width:'280px',height: '200px'}">
        
      </div>
      
    </div>
  </template>
  
  <script>
  import * as echarts from "echarts";
  import {onUnmounted, onMounted, reactive, watch } from 'vue'
  
  export default {
    props: {
        weekNumbr: {   // 柱状图数据
            type: Array,
            default() {
                return []
            }
        },
        xAxis: {   // 柱状图x轴
            type: Array,
            default() {
                return []
            }
        },
    },
    //setup能接收到两个参数,第一个就是props
    setup(props) {
      //echarts图表的基本数据
      const info = reactive({
        options:{
          xAxis: {
                type: 'category',
                data: props.xAxis,
                axisTick: {
                    show: false
                }, 
            },
            yAxis: {
                type: 'value',
                splitLine:{
                    show:false
                },
                show:false
            },
            series: [
                {
                data: props.weekNumbr,
                type: 'bar',
                barWidth: '45%',
                itemStyle:{
                    color:'#1FD286',
                    borderRadius: 4
                }
                }
            ]

        }
      })
      
      /// 声明定义一下echart
      let echart = echarts;
      
      onMounted(() => {
        initChart();
      });
  
      onUnmounted(() => {
        echart.dispose;
      });
      
      // 基础配置一下Echarts
      function initChart() {
        let chart = echart.init(document.getElementById("bar"), "#000");
        // 把配置和数据放这里
        chart.setOption(info.options)
        window.onresize = function() {
            //自适应大小
            chart.resize();
        };
      }
      //监听父组件数据变化,重绘echarts图表,可以在父组件写个++功能试试
      watch([props.weekNumbr,props.xAxis],() => {
          initChart()
          // alert('监听到了'),
          // console.log(newVal,oldVal);
          //console.log("info中的内容是",props);

      })
        //return定义的函数,变量
        return { info, initChart };
          }
  
  }
  
  </script>
    
  <style scoped>
    .echarts_class{
        display: flex;
        justify-content: flex-end;
        align-items: flex-end;
        /* position: relative; */
    }
    
  </style>
  

效果图

 

 父组件静态数据可实现,父组组件异步接口获取数据的时候可能导致绘制不出来图像的问题,那个时候需要再加判断,确定获取到props数据再渲染,目前代码里没有体现

猜你喜欢

转载自blog.csdn.net/weixin_46764819/article/details/128282256