vue实现柱形图
使用 ECharts 实现柱形图
安装 ECharts 依赖:
npm install echarts --save
在 Vue 组件中引入 ECharts:
import * as echarts from 'echarts';
创建柱形图容器:
<template>
<div id="barChart" style="width: 600px; height: 400px;"></div>
</template>
初始化图表并配置数据:
export default {
mounted() {
this.initBarChart();
},
methods: {
initBarChart() {
const chartDom = document.getElementById('barChart');
const myChart = echarts.init(chartDom);
const option = {
title: {
text: '柱形图示例'
},
tooltip: {},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
yAxis: {},
series: [
{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}
]
};
myChart.setOption(option);
}
}
}
使用 Vue-ECharts 封装组件
安装 vue-echarts:
npm install echarts vue-echarts
创建可复用的柱形图组件:
import ECharts from 'vue-echarts';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart } from 'echarts/charts';
import {
GridComponent,
TooltipComponent,
TitleComponent,
LegendComponent
} from 'echarts/components';
use([
CanvasRenderer,
BarChart,
GridComponent,
TooltipComponent,
TitleComponent,
LegendComponent
]);
export default {
components: {
'v-chart': ECharts
},
props: {
chartData: {
type: Object,
required: true
}
},
data() {
return {
options: {
title: {
text: this.chartData.title
},
tooltip: {},
xAxis: {
data: this.chartData.categories
},
yAxis: {},
series: [
{
name: this.chartData.seriesName,
type: 'bar',
data: this.chartData.values
}
]
}
};
}
}
使用组件:
<template>
<v-chart :options="options" autoresize />
</template>
响应式处理
添加窗口大小变化监听:
mounted() {
window.addEventListener('resize', this.handleResize);
this.initChart();
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
if (this.myChart) {
this.myChart.resize();
}
}
}
动态更新数据
使用 watch 监听数据变化:
watch: {
chartData: {
deep: true,
handler(newVal) {
if (this.myChart) {
const option = this.myChart.getOption();
option.xAxis[0].data = newVal.categories;
option.series[0].data = newVal.values;
this.myChart.setOption(option);
}
}
}
}
自定义样式配置
修改柱形图颜色和样式:
series: [
{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20],
itemStyle: {
color: '#5470c6',
barBorderRadius: [4, 4, 0, 0]
},
emphasis: {
itemStyle: {
color: '#83a0ed'
}
}
}
]
添加渐变色效果:
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#83bff6' },
{ offset: 0.5, color: '#188df0' },
{ offset: 1, color: '#188df0' }
])
}






