vue实现柱形图
Vue 中使用 ECharts 实现柱形图
安装 ECharts 依赖
npm install echarts --save
引入 ECharts 并初始化图表
import * as echarts from 'echarts';
在 Vue 组件中创建图表容器
<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: {},
legend: {
data: ['销量']
},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
yAxis: {},
series: [
{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}
]
};
myChart.setOption(option);
}
}
}
响应式调整
添加窗口大小变化监听
methods: {
initBarChart() {
// ...之前的初始化代码
window.addEventListener('resize', function() {
myChart.resize();
});
}
}
使用 Vue-ECharts 封装组件
安装 vue-echarts

npm install vue-echarts
封装可复用组件
<template>
<v-chart :option="option" autoresize />
</template>
<script>
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart } from 'echarts/charts';
import {
TitleComponent,
TooltipComponent,
LegendComponent,
GridComponent
} from 'echarts/components';
import VChart from 'vue-echarts';
use([
CanvasRenderer,
BarChart,
TitleComponent,
TooltipComponent,
LegendComponent,
GridComponent
]);
export default {
components: { VChart },
data() {
return {
option: {
// 同上配置
}
}
}
}
</script>
动态数据更新
通过 props 传递数据
props: {
chartData: {
type: Array,
required: true
},
xAxisData: {
type: Array,
required: true
}
},
watch: {
chartData: {
handler(newVal) {
this.option.series[0].data = newVal;
this.$refs.chart.setOption(this.option);
},
deep: true
}
}
自定义样式配置
设置柱形图样式
option: {
series: [{
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#83bff6' },
{ offset: 0.5, color: '#188df0' },
{ offset: 1, color: '#188df0' }
])
},
emphasis: {
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#2378f7' },
{ offset: 0.7, color: '#2378f7' },
{ offset: 1, color: '#83bff6' }
])
}
}
}]
}






