用vue实现echarts
使用 Vue 实现 ECharts
安装依赖
确保项目已安装 Vue 和 ECharts。通过以下命令安装 ECharts:
npm install echarts --save
引入 ECharts
在 Vue 组件中引入 ECharts:
import * as echarts from 'echarts';
创建图表容器
在模板中添加一个用于渲染图表的 DOM 元素:
<template>
<div ref="chart" style="width: 600px; height: 400px;"></div>
</template>
初始化图表
在 mounted 生命周期钩子中初始化图表:
export default {
mounted() {
this.initChart();
},
methods: {
initChart() {
const chartDom = this.$refs.chart;
const myChart = echarts.init(chartDom);
const option = {
title: {
text: '示例图表'
},
tooltip: {},
xAxis: {
data: ['A', 'B', 'C', 'D', 'E']
},
yAxis: {},
series: [
{
name: '数据',
type: 'bar',
data: [5, 20, 36, 10, 15]
}
]
};
myChart.setOption(option);
}
}
};
响应式调整
监听窗口大小变化,动态调整图表尺寸:
methods: {
initChart() {
const chartDom = this.$refs.chart;
const myChart = echarts.init(chartDom);
// ...选项配置
window.addEventListener('resize', () => {
myChart.resize();
});
}
}
销毁图表
在组件销毁前移除监听器并释放资源:
beforeDestroy() {
if (this.myChart) {
window.removeEventListener('resize', this.myChart.resize);
this.myChart.dispose();
}
}
按需引入 ECharts
若需优化体积,可按需引入模块:
import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([BarChart, TitleComponent, TooltipComponent, GridComponent, CanvasRenderer]);
封装为可复用组件
将图表逻辑封装为全局或局部组件:
Vue.component('vue-echarts', {
props: ['option'],
template: '<div ref="chart" style="width: 100%; height: 100%;"></div>',
mounted() {
this.chart = echarts.init(this.$refs.chart);
this.chart.setOption(this.option);
},
watch: {
option: {
handler(newVal) {
this.chart.setOption(newVal);
},
deep: true
}
}
});






