美文网首页Frontend前端
7、vue3+ts封装echarts

7、vue3+ts封装echarts

作者: 蜗牛的学习方法 | 来源:发表于2023-02-16 09:08 被阅读0次

封装echarts是一般项目都会使用到的一些插件,所以我封装了一个echarts组件

//echart/index.vue
<template>
  <div ref="echartDivRef" class="echart"></div>
</template>

<script lang="ts" setup>
import { onMounted, ref, Ref, watch } from "vue";
import * as echarts from "echarts";
import {
  ECharts,
  GridComponentOption,
  LineSeriesOption,
  BarSeriesOption,
} from "echarts";

//这个地方这样写是为了防止ts监测到类型不匹配的问题
type EChartsOption = echarts.ComposeOption<
  GridComponentOption | LineSeriesOption | BarSeriesOption
>;

const echartDivRef = ref<HTMLDivElement>();
let myChart: ECharts;

const props = withDefaults(
  defineProps<{
    options: EChartsOption;
  }>(),
  {
    options: () => ({}),
  }
);

const initChart = () => {
  if (myChart !== undefined) {
    myChart.dispose();
  }
  myChart = echarts.init(echartDivRef.value as HTMLDivElement);
  myChart.setOption(props.options);
};

const updateSize = () => {
  myChart.resize();
};

watch(
  () => props.options,
  () => {
    initChart();
  },
  {
    deep: true,
  }
);

onMounted(() => {
  initChart();
  window.addEventListener("resize", () => {
    myChart.resize();
  });
});

defineExpose({
  updateSize,
});
</script>

<style lang="css" scoped>
.echart {
  width: 100%;
  height: 100%;
}
</style>

使用

<template>
  <div class="main">
    <div class="echarts">
      <Charts :options="options" />
    </div>
    <a-button @click="handleChange">点击</a-button>
  </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import {
  GridComponentOption,
  LineSeriesOption,
  BarSeriesOption,
} from "echarts";

import Charts from "./components/echarts/index.vue";
//这个地方这样写是为了防止ts监测到类型不匹配的问题,同时与组件里面的类型声明保持一致
type EChartsOption = echarts.ComposeOption<
  GridComponentOption | LineSeriesOption | BarSeriesOption
>;

let options = ref<EChartsOption>({
  xAxis: {
    type: "category",
    data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
  },
  yAxis: {
    type: "value",
  },
  series: [
    {
      data: [150, 230, 224, 218, 135, 147, 260],
      type: "line",
    },
  ],
});

const handleChange = () => {
  let data: Array<number> = [];
  for (let i = 0; i < 7; i++) {
    data.push(Math.ceil(Math.random() * 100));
  }
  options.value.series = [
    {
      data: data,
      type: "bar",
    },
  ];
};
</script>

<style scoped>
.main {
  width: 100%;
  height: 100%;
}
.echarts {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>

最后效果图:

相关文章

网友评论

    本文标题:7、vue3+ts封装echarts

    本文链接:https://www.haomeiwen.com/subject/ypcpkdtx.html