<script setup name="charts">
import {
  ref,
  nextTick,
  watch,
  onMounted,
  onBeforeUnmount,
} from "vue";
import * as echarts from "echarts";
import { debounce } from '@/utils/common';

const props = defineProps({
  option: {
    //配置对象
    type: Object,
    default: () => {},
  },
  clickEvent: {
    //点击事件
    type: Function,
    default: () => {},
  },
  mouseleaveEvent: {
    //鼠标移除事件
    type: Function,
    default: () => {},
  },
  mouseoverEvent: {
    //鼠标移入事件
    type: Function,
    default: () => {},
  },
});

const controller = new AbortController()
const { signal } = controller;
let myChart = null;
const domKey = `A${parseInt(new Date().getTime() * (Math.random() * 1000))}`;
const [resizeHandler] = [ref(null)];

/* 绘制图表 */
function drawChart() {
  nextTick(() => {
    const element = document.getElementById(domKey);
    myChart = echarts.init(element);
    resizeHandler.value = debounce(()=>myChart?.resize(),200)
    window.addEventListener("resize", resizeHandler.value,{ signal });

    myChart.setOption(props.option, true);
    myChart.on("mouseover", props.mouseoverEvent);
    myChart.on("click", props.clickEvent);
    myChart.on("mouseout", props.mouseleaveEvent);
  });
}

watch(
  () => props.option,
  () => drawChart(),
  { deep: true }
);

onMounted(() => drawChart());
onBeforeUnmount(() => controller.abort());
</script>

<template>
  <div :id="domKey" class="myChart"></div>
</template>

<style scoped>
.myChart {
  width: 100%;
  height: 100%;
}
</style>

九霄
154 声望13 粉丝

记录开发以来,遇到的一些问题...