vue实现echarts项目
vue3 中集成 ECharts
安装 ECharts 依赖包
npm install echarts --save
在组件中引入并初始化
import * as echarts from 'echarts';
import { onMounted, ref } from 'vue';
const chartRef = ref(null);
onMounted(() => {
const myChart = echarts.init(chartRef.value);
myChart.setOption({
title: { text: 'Vue3 ECharts 示例' },
tooltip: {},
xAxis: { data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子'] },
yAxis: {},
series: [{ name: '销量', type: 'bar', data: [5, 20, 36, 10, 10, 20] }]
});
});
模板部分
<div ref="chartRef" style="width: 600px; height: 400px;"></div>
响应式处理
监听窗口变化自动调整
import { onUnmounted } from 'vue';
const resizeHandler = () => myChart.resize();
window.addEventListener('resize', resizeHandler);
onUnmounted(() => {
window.removeEventListener('resize', resizeHandler);
myChart.dispose();
});
封装可复用组件
创建 EChartsWrapper.vue
<template>
<div ref="chartEl" :style="{ width, height }"></div>
</template>
<script setup>
import * as echarts from 'echarts';
import { ref, watch, onMounted, onUnmounted } from 'vue';
const props = defineProps({
option: Object,
width: { type: String, default: '100%' },
height: { type: String, default: '400px' }
});
const chartEl = ref(null);
let chartInstance = null;
const initChart = () => {
chartInstance = echarts.init(chartEl.value);
chartInstance.setOption(props.option);
};
onMounted(initChart);
onUnmounted(() => chartInstance?.dispose());
watch(() => props.option, (newVal) => {
chartInstance?.setOption(newVal);
}, { deep: true });
</script>
主题定制
使用官方主题
import * as echarts from 'echarts';
import 'echarts/theme/dark'; // 引入暗黑主题
const myChart = echarts.init(chartRef.value, 'dark');
自定义主题
- 在主题编辑器中设计:https://echarts.apache.org/theme-builder.html
- 下载主题文件并导入
import theme from './customTheme.json'; echarts.registerTheme('myTheme', theme); const myChart = echarts.init(chartRef.value, 'myTheme');
常见图表类型实现
折线图配置示例
{
xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] },
yAxis: { type: 'value' },
series: [{ data: [820, 932, 901, 934, 1290, 1330, 1320], type: 'line' }]
}
饼图配置示例
{
series: [{
type: 'pie',
data: [
{ value: 1048, name: 'Search Engine' },
{ value: 735, name: 'Direct' },
{ value: 580, name: 'Email' }
]
}]
}
性能优化建议
大数据量使用增量渲染
series: [{
type: 'line',
progressive: 1000, // 增量渲染阈值
progressiveThreshold: 1000
}]
按需引入模块
import * as echarts from 'echarts/core';
import { BarChart, LineChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([BarChart, LineChart, TitleComponent, TooltipComponent, CanvasRenderer]);






