vue3 Echarts通用组件

概要

提示:针对不需要复用只在单一页面应用的图表(多页面应用还是做个小组件 )

因为写的Echarts图表很多,每一个图表就创建一个vue页面,很多很杂,所以想要创建一个公用的Echarts 只需要传值一个options就可以

组件构思

提示:只是简单的图表展示(需要加点击事件什么的,自己加)

在这里插入图片描述
定义props传值

chartDataOptions:接受options值,默认为null

  props: {
    // 接收父组件传递过来的信息
    chartDataOptions: {
      type: Object, // 此处可以为Array或者Object或者其它,根据需求来。
      default: null
    }
  },

难点汇总

  • 一个页面多次使用的时候,要正确显示
    只使用id来进行渲染Echarts会出现只显示一个图表的问题
	两个方案,使用ref渲染,或者给每一个Echarts随机赋值id

我这采用随机id的方式赋值渲染

 computed: {
    echartsComponents() {
      const timestamp = new Date().getTime();
      return `echarts${timestamp}${Math.random() * 100000}`;
    }
  },
  • 当数据传输过慢或切换options里面的数据,Echarts图表不渲染或重新渲染无效

使用watch监听刷新和$nextTick操作新实例

  watch: {
    chartDataOptions: {
      handler() {
        this.refreshEcharts();
      },
      deep: true
    }
  },
  mounted() {
    this.initEcharts();
    this.$nextTick(() => {
      this.refreshEcharts();
    });
  },

通用组件代码

提示:记得清空和摧毁一下Echarts实例,养成好习惯

<template>
  <div
    v-if="!isDispose"
    :id="echartsComponents"
    style="width: 100%;height: 100%"
  />
</template>

<script>
export default {
  name: "EchartsComes",
  props: {
    // 接收父组件传递过来的信息
    chartDataOptions: {
      type: Object, // 此处可以为Array或者Object或者其它,根据需求来。
      default: null
    }
  },
  data() {
    return {
      myEcharts: null,
      isDispose: false
    };
  },
  computed: {
    echartsComponents() {
      const timestamp = new Date().getTime();
      return `echarts${timestamp}${Math.random() * 100000}`;
    }
  },
  watch: {
    chartDataOptions: {
      handler() {
        this.refreshEcharts();
      },
      deep: true
    }
  },
  mounted() {
    this.initEcharts();
    this.$nextTick(() => {
      this.refreshEcharts();
    });
  },
  beforeDestroy() {
    if (this.myEcharts) {
      this.myEcharts.clear();
      this.myEcharts.dispose();
      this.isDispose = true;
    }
  },
  methods: {
    initEcharts() {
      this.isDispose = false;
      const $echartsDOM = document.getElementById(this.echartsComponents);
      this.myEcharts = this.$echarts.init($echartsDOM);
      this.refreshEcharts();
    },
    // 图表刷新
    refreshEcharts() {
      // 渲染数据
      const option = this.chartDataOptions;
      this.myEcharts.clear();
      this.myEcharts.setOption(option);
    }
  }
};
</script>

父组件调用

 <card :title="'按检查内容统计安全检测'">
        <template #zero>
          <echarts-com :chart-data-options="zxtOption" />
        </template>
      </card>

效果图展示

在这里插入图片描述

		雅,实在是太优雅了~
  • 12
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哈维的魔幻城堡

各位彭于晏们帮助孩子吃个馒头吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值