vue.js实现echarts
Vue.js 中集成 ECharts 的方法
安装依赖 在 Vue.js 项目中安装 ECharts 核心库和 Vue-ECharts 封装库(可选):
npm install echarts vue-echarts
基础集成方式(直接使用 ECharts)
创建组件时在 mounted 生命周期初始化图表:
<template>
<div ref="chartDom" style="width: 600px; height: 400px;"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
mounted() {
const chart = echarts.init(this.$refs.chartDom);
chart.setOption({
xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed'] },
yAxis: { type: 'value' },
series: [{ data: [820, 932, 901], type: 'line' }]
});
}
};
</script>
使用 vue-echarts 封装组件
注册全局组件 在 main.js 中全局注册更简洁的组件:

import Vue from 'vue';
import ECharts from 'vue-echarts';
import 'echarts';
Vue.component('v-chart', ECharts);
组件模板用法 直接在模板中使用声明式配置:
<template>
<v-chart
:option="chartOption"
:autoresize="true"
style="width: 100%; height: 400px;"
/>
</template>
<script>
export default {
data() {
return {
chartOption: {
tooltip: {},
series: [{ type: 'pie', data: [{ value: 335, name: 'A' }]}]
}
}
}
};
</script>
响应式处理技巧
监听数据变化 当需要动态更新图表时,使用 watch 或 computed:

watch: {
dataSource(newVal) {
this.chart.setOption({ series: [{ data: newVal }] });
}
}
窗口尺寸自适应 添加 resize 事件监听确保响应式:
mounted() {
window.addEventListener('resize', this.handleResize);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
this.chart && this.chart.resize();
}
}
性能优化建议
按需引入模块 减少打包体积:
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import { GridComponent } from 'echarts/components';
echarts.use([LineChart, GridComponent]);
大数剧处理 对于海量数据考虑使用增量渲染:
series: {
type: 'scatter',
progressive: 1000,
progressiveThreshold: 3000
}






