柱状图vue实现
使用 Vue 和 ECharts 实现柱状图
安装 ECharts 依赖:
npm install echarts --save
在 Vue 组件中引入 ECharts:
import * as echarts from 'echarts';
创建基础柱状图组件:
<template>
<div ref="chartDom" style="width: 600px; height: 400px;"></div>
</template>
<script>
export default {
mounted() {
this.initChart();
},
methods: {
initChart() {
const chartDom = this.$refs.chartDom;
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);
}
}
}
</script>
响应式柱状图实现
添加窗口大小变化监听:
mounted() {
this.initChart();
window.addEventListener('resize', this.handleResize);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
this.myChart.resize();
}
}
动态数据柱状图
通过 props 接收动态数据:
props: {
chartData: {
type: Object,
required: true
}
},
watch: {
chartData: {
deep: true,
handler(newVal) {
this.updateChart(newVal);
}
}
},
methods: {
updateChart(data) {
this.myChart.setOption({
xAxis: {
data: data.categories
},
series: [{
data: data.values
}]
});
}
}
多系列柱状图实现
配置多个系列数据:
const option = {
xAxis: {
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
},
yAxis: {},
series: [
{
name: '线上',
type: 'bar',
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: '线下',
type: 'bar',
data: [220, 182, 191, 234, 290, 330, 310]
}
]
};
自定义样式柱状图
添加样式配置:
series: [{
name: '销量',
type: 'bar',
itemStyle: {
color: '#4ad8ff',
borderRadius: [4, 4, 0, 0]
},
barWidth: '40%',
data: [5, 20, 36, 10, 10, 20]
}]
使用 Vue-ECharts 封装组件
安装 vue-echarts:
npm install echarts vue-echarts
创建可复用组件:
<template>
<v-chart :option="chartOption" 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 },
props: {
data: Array,
categories: Array
},
computed: {
chartOption() {
return {
xAxis: {
type: 'category',
data: this.categories
},
yAxis: {
type: 'value'
},
series: [{
data: this.data,
type: 'bar'
}]
};
}
}
};
</script>






