vue实现条形图
使用 ECharts 实现条形图
安装 ECharts 依赖
npm install echarts --save
在 Vue 组件中引入 ECharts
import * as echarts from 'echarts';
创建基础条形图组件

<template>
<div ref="chart" style="width: 600px; height: 400px;"></div>
</template>
<script>
export default {
mounted() {
this.initChart();
},
methods: {
initChart() {
const chartDom = this.$refs.chart;
const myChart = echarts.init(chartDom);
const option = {
title: {
text: '销售数据统计'
},
tooltip: {},
xAxis: {
type: 'value'
},
yAxis: {
type: 'category',
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
series: [
{
name: '销量',
type: 'bar',
data: [120, 200, 150, 80, 70, 110]
}
]
};
myChart.setOption(option);
}
}
};
</script>
使用 Vue-ECharts 封装组件
安装 vue-echarts
npm install echarts vue-echarts
创建可复用的条形图组件

<template>
<v-chart :option="chartOption" autoresize />
</template>
<script>
import { use } from 'echarts/core';
import { BarChart } from 'echarts/charts';
import {
TitleComponent,
TooltipComponent,
GridComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import VChart from 'vue-echarts';
use([
TitleComponent,
TooltipComponent,
GridComponent,
BarChart,
CanvasRenderer
]);
export default {
components: {
VChart
},
data() {
return {
chartOption: {
title: {
text: '月度销售数据'
},
tooltip: {
trigger: 'axis'
},
xAxis: {
type: 'value'
},
yAxis: {
type: 'category',
data: ['一月', '二月', '三月', '四月', '五月', '六月']
},
series: [
{
name: '销售额',
type: 'bar',
data: [3200, 4200, 3500, 3800, 4100, 4600],
itemStyle: {
color: '#3398DB'
}
}
]
}
};
}
};
</script>
响应式数据绑定
动态更新条形图数据
export default {
data() {
return {
chartData: {
categories: ['产品A', '产品B', '产品C', '产品D'],
values: [45, 78, 62, 93]
}
};
},
computed: {
chartOption() {
return {
xAxis: {
type: 'value'
},
yAxis: {
type: 'category',
data: this.chartData.categories
},
series: [
{
type: 'bar',
data: this.chartData.values,
label: {
show: true,
position: 'right'
}
}
]
};
}
},
methods: {
updateData() {
// 模拟数据更新
this.chartData.values = this.chartData.values.map(
value => value + Math.floor(Math.random() * 20)
);
}
}
};
水平条形图配置
将条形图改为水平显示
const option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [120, 200, 150, 80, 70, 110, 130],
type: 'bar',
showBackground: true,
backgroundStyle: {
color: 'rgba(180, 180, 180, 0.2)'
}
}
]
};
多系列条形图
展示多个数据系列的对比
const option = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
legend: {
data: ['2020年', '2021年']
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'value'
},
yAxis: {
type: 'category',
data: ['巴西', '印尼', '美国', '印度', '中国', '世界']
},
series: [
{
name: '2020年',
type: 'bar',
data: [18203, 23489, 29034, 104970, 131744, 630230]
},
{
name: '2021年',
type: 'bar',
data: [19325, 23438, 31000, 121594, 134141, 681807]
}
]
};






