echarts图表通用组件封装

封装echarts图表,使图表盒子能自适应尺寸并自动销毁等

<template>
  <div
    class="echart-comp-box"
    ref="chartDom"
    :style="{
      width: typeof ewidth === 'string' ? ewidth : ewidth + '%',
      height: typeof eheight === 'string' ? eheight : eheight + '%'
    }"
  ></div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount, defineProps, watch, nextTick } from 'vue'
import * as echarts from 'echarts'

//获取 dom 和 父组件数据 并定义"myChart"用于初始化图表
const chartDom = ref()
let myChart = null

const props = defineProps({
  option: Object,
  ewidth: [Number, String], // 容器宽度, 字符串直接展示, 数字类型为%展示
  eheight: [Number, String] // 容器高度
})

//监听图表数据时候变化,重新渲染图表
watch(
  () => props.option,
  (newV) => {
    if (myChart) {
      myChart.setOption(props.option, true)
    } else {
      initChart()
    }
  },
  { deep: true }
)

//重绘图表函数
const resizeHandler = () => {
  myChart.resize()
}

//设置防抖,保证无论拖动窗口大小,只执行一次获取浏览器宽高的方法
const debounce = (fun, delay) => {
  let timer
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fun()
    }, delay)
  }
}

const cancalDebounce = debounce(resizeHandler, 500)

//页面成功渲染,开始绘制图表
onMounted(() => {
  initChart()
})
const initChart = () => {
  if (chartDom.value) {
    chartDom.value.setAttribute('_echarts_instance_', '')
    // 配置为 svg 形式,预防页面缩放而出现模糊问题;图表过于复杂时建议使用 Canvas
    myChart = echarts.init(chartDom.value, null, { renderer: 'svg' })
    // myChart = echarts.init(chartDom.value)
    props.option && myChart.setOption(props.option, true)
    // 自适应不同屏幕时改变图表尺寸
    window.addEventListener('resize', cancalDebounce)
  }
}
//页面销毁前,销毁事件和实例
onBeforeUnmount(() => {
  window.removeEventListener('resize', cancalDebounce)
  myChart?.dispose()
})
</script>
<style lang="scss" scoped>
.echart-comp-box {
  width: 100%;
  height: 100%;
}
</style>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容