赞
踩
在项目的开发中需要使用echart完成数据的可视化展示,因为只是使用到折线图和柱状图,但是在打包的时候,发现echart会全部打包进去,为减少编译后的包体积进行相关设置的配置。(当然除了设置按需引入,也可以使用cdn的方式,此篇不涉及)
pnpm i echart --save-dev
在util中新建commonEchart.ts
// 引入 echarts 核心模块,核心模块提供了 echarts 使用必须要的接口。 import * as echarts from "echarts/core"; /** 引入柱状图and折线图图表,图表后缀都为 Chart */ import { BarChart, LineChart } from "echarts/charts"; // 引入提示框,标题,直角坐标系,数据集,内置数据转换器组件,组件后缀都为 Component import { TitleComponent, TooltipComponent, GridComponent, DatasetComponent, TransformComponent, } from "echarts/components"; // 标签自动布局,全局过渡动画等特性 import { LabelLayout, UniversalTransition } from "echarts/features"; // 引入 Canvas 渲染器,注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步 import { CanvasRenderer } from "echarts/renderers"; // 注册必须的组件 echarts.use([ TitleComponent, TooltipComponent, GridComponent, DatasetComponent, TransformComponent, BarChart, LabelLayout, UniversalTransition, CanvasRenderer, LineChart, ]); // 导出 export default echarts;
把echart 设置成组件
myChart.vue <template> <div ref="chartRef" class="my-chart"></div> </template> <script setup lang="ts"> import { defineProps, onBeforeUnmount, onMounted, ref } from "vue"; import echarts from "../../utils/commonEchart"; const props = defineProps(["options"]); const chartRef = ref<HTMLDivElement>(); let chart: echarts.ECharts | null = null; const resizeHandler = () => { chart?.resize(); }; onMounted(() => { setTimeout(() => { initChart(); }, 20); window.addEventListener("resize", resizeHandler); }); const initChart = () => { chart = echarts.init(chartRef.value as HTMLDivElement); chart.setOption({ ...props.options, }); }; onBeforeUnmount(() => { window.removeEventListener("resize", resizeHandler); chart?.dispose(); }); </script> <style lang="scss" scoped></style>
在需要使用的页面中
<template> <div> <my-echart :options="options7" class="h-right-three-chart"></my-echart> </div> </template> <script lang="ts"> import MyEchart from "../../components/MyEchart.vue"; export default { components: { MyEchart }, setup() { const options7 = { title: { text: "ECharts 入门示例", }, tooltip: {}, xAxis: { data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], }, yAxis: {}, series: [ { name: "销量", type: "bar", data: [5, 20, 36, 10, 10, 20], }, ], }; return { options7, }; }, }; </script> <style scoped> .h-right-three-chart { width: 100%; height: 352px; } </style>
在vite.config.ts的build通过设置 manualChunks方案,将echarts单独打包并通过按需引入减少主包体积
build: {
rollupOptions: {
output: {
manualChunks: {
echarts: ['echarts']
}
},
},
},
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。