用vue实现echarts
使用 Vue 实现 ECharts
安装依赖
在 Vue 项目中安装 ECharts 和 Vue-ECharts(官方推荐的 Vue 封装库):
npm install echarts vue-echarts
全局注册组件
在 main.js 或入口文件中全局注册 Vue-ECharts:
import { createApp } from 'vue'
import App from './App.vue'
import ECharts from 'vue-echarts'
import 'echarts'
const app = createApp(App)
app.component('v-chart', ECharts)
app.mount('#app')
基础使用示例
在 Vue 组件中直接使用 <v-chart> 组件:

<template>
<v-chart :option="chartOption" class="chart" />
</template>
<script>
export default {
data() {
return {
chartOption: {
title: { text: '示例图表' },
tooltip: {},
xAxis: { data: ['A', 'B', 'C', 'D', 'E'] },
yAxis: {},
series: [{ name: '销量', type: 'bar', data: [5, 20, 36, 10, 15] }]
}
}
}
}
</script>
<style>
.chart {
width: 600px;
height: 400px;
}
</style>
动态更新数据
通过修改 chartOption 实现动态数据更新:
methods: {
updateData() {
this.chartOption.series[0].data = [10, 25, 40, 15, 20]
}
}
响应式布局
监听窗口变化自动调整图表大小:

mounted() {
window.addEventListener('resize', this.handleResize)
},
beforeUnmount() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
this.$refs.chart.resize()
}
}
按需引入模块
减少打包体积,只引入需要的 ECharts 模块:
import * as echarts from 'echarts/core'
import { BarChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
echarts.use([TitleComponent, TooltipComponent, BarChart, CanvasRenderer])
主题定制
使用自定义主题或官方主题:
import 'echarts/theme/dark'
// 使用时
<v-chart :option="chartOption" theme="dark" />
事件绑定
监听图表事件:
<v-chart
:option="chartOption"
@click="handleChartClick"
/>
methods: {
handleChartClick(params) {
console.log('图表点击事件', params)
}
}






