vue实现动态图表
使用 Vue 和 ECharts 实现动态图表
安装 ECharts 依赖
npm install echarts --save
在 Vue 组件中引入 ECharts
import * as echarts from 'echarts';
创建图表容器
<div ref="chartRef" style="width: 600px; height: 400px;"></div>
初始化图表
export default {
mounted() {
this.initChart();
},
methods: {
initChart() {
const chartDom = this.$refs.chartRef;
const myChart = echarts.init(chartDom);
const option = {
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'
}]
};
myChart.setOption(option);
}
}
}
实现动态数据更新
添加定时更新数据的方法
methods: {
// ...其他方法
updateData() {
const newData = Array(7).fill(0).map(() => Math.round(Math.random() * 1000));
this.myChart.setOption({
series: [{
data: newData
}]
});
}
},
mounted() {
this.initChart();
this.timer = setInterval(this.updateData, 2000);
},
beforeDestroy() {
clearInterval(this.timer);
this.myChart.dispose();
}
使用 Vue-ECharts 封装组件
安装 vue-echarts
npm install vue-echarts
创建可复用的图表组件
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart } from 'echarts/charts';
import {
TitleComponent,
TooltipComponent,
LegendComponent,
GridComponent
} from 'echarts/components';
import VChart from 'vue-echarts';
use([
CanvasRenderer,
LineChart,
TitleComponent,
TooltipComponent,
LegendComponent,
GridComponent
]);
export default {
components: {
VChart
},
props: {
chartData: {
type: Array,
required: true
}
},
computed: {
options() {
return {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: this.chartData,
type: 'line'
}]
};
}
}
};
响应式图表实现
监听窗口大小变化
mounted() {
window.addEventListener('resize', this.handleResize);
this.handleResize();
},
methods: {
handleResize() {
this.myChart && this.myChart.resize();
}
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
}
多图表类型支持
配置不同图表类型的选项
const option = {
tooltip: {},
legend: {
data: ['销量']
},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
yAxis: {},
series: [
{
name: '销量',
type: 'bar', // 可改为 'pie', 'line', 'scatter' 等
data: [5, 20, 36, 10, 10, 20]
}
]
};






