【前端】【组件】【vue2】封装一个vue2的ECharts组件,不用借助vue-echarts
在Vue2项目中使用ECharts 5.6的完整实现步骤如下:
- 安装依赖
npm install echarts@5.6.2 --save # 指定安装5.x最新版本
- 基础组件实现(新建
components/ECharts.vue
)
<template>
<div ref="chartDom" class="echarts-container"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
props: {
options: { // 接收父组件传入的配置
type: Object,
required: true
}
},
data() {
return {
chartInstance: null // 存储图表实例
};
},
mounted() {
this.initChart();
window.addEventListener('resize', this.handleResize); // 响应式处理
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize); // 清理事件监听
if (this.chartInstance) {
this.chartInstance.dispose(); // 销毁实例
}
},
methods: {
initChart() {
this.chartInstance = echarts.init(this.$refs.chartDom);
this.chartInstance.setOption(this.options);
},
handleResize() {
this.chartInstance?.resize(); // ES2020可选链操作符
}
},
watch: { // 监听options变化
options: {
deep: true,
handler(newVal) {
this.chartInstance?.setOption(newVal);
}
}
}
};
</script>
<style scoped>
.echarts-container {
width: 100%;
height: 400px; /* 默认高度 */
}
</style>
- 使用示例(在父组件中):
<template>
<div>
<ECharts :options="chartOptions" />
</div>
</template>
<script>
import ECharts from '@/components/ECharts.vue';
export default {
components: { ECharts },
data() {
return {
chartOptions: {
title: {
text: '销售趋势分析',
left: 'center'
},
tooltip: {
trigger: 'axis'
},
xAxis: {
type: 'category',
data: ['1月', '2月', '3月', '4月', '5月', '6月']
},
yAxis: {
type: 'value'
},
series: [{
name: '销售额',
type: 'line',
data: [820, 932, 901, 934, 1290, 1330],
smooth: true,
areaStyle: {}
}]
}
};
}
};
</script>
关键优化点:
- 响应式设计:自动监听窗口resize事件并调整图表尺寸
- 配置更新:通过watch深度监听options变化实现动态更新
- 内存管理:在组件销毁时正确释放图表资源
- 错误处理:使用可选链操作符避免空值错误
扩展建议:
- 按需引入:通过
echarts/core
实现按需打包
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart } from 'echarts/charts';
import {
TitleComponent,
TooltipComponent,
GridComponent,
LegendComponent
} from 'echarts/components';
use([
CanvasRenderer,
LineChart,
TitleComponent,
TooltipComponent,
GridComponent,
LegendComponent
]);
- 主题定制:可注册自定义主题
// 在main.js中
import theme from './echarts-theme.json';
echarts.registerTheme('myTheme', theme);
// 组件中使用
this.chartInstance = echarts.init(this.$refs.chartDom, 'myTheme');
- 性能优化:大数据量时启用大数据模式
series: [{
type: 'line',
large: true, // 开启大数据优化
largeThreshold: 2000, // 数据量>2000时启用
// ...
}]