You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

126 lines
2.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<template>
<div class="bar-chart">
<!-- 图表容器 -->
<div ref="chartDom" class="chart-container"></div>
</div>
</template>
<script>
import echarts from 'echarts'; // 需安装npm install echarts@4.9.0
export default {
name: 'BarChart',
props: {
// X轴数据必传数组格式['项目A', '项目B']
xAxisData: {
type: Array,
required: true,
default: () => []
},
// Y轴数据必传包含三组数据格式如下
seriesData: {
type: Array,
required: true,
// 格式示例:
// [
// { name: '年初预算合计金额', data: [5000, 8000] },
// { name: '调整后预算合计金额', data: [6000, 7500] },
// { name: '已使用', data: [3000, 5000] }
// ]
default: () => []
}
},
data() {
return {
chartInstance: null // 图表实例
};
},
watch: {
// 监听数据变化,实时更新图表
xAxisData: {
deep: true,
handler() {
this.updateChart();
}
},
seriesData: {
deep: true,
handler() {
this.updateChart();
}
}
},
mounted() {
// 初始化图表
this.$nextTick(() => {
this.initChart();
});
},
beforeDestroy() {
// 销毁图表实例
if (this.chartInstance) {
this.chartInstance.dispose();
}
},
methods: {
// 初始化图表
initChart() {
this.chartInstance = echarts.init(this.$refs.chartDom);
this.updateChart();
},
// 更新图表数据
updateChart() {
if (!this.chartInstance) return;
const option = {
tooltip: {
trigger: 'axis',
axisPointer: { type: 'shadow' } // 阴影指示器
},
legend: {
// 图例使用 seriesData 中的 name
data: this.seriesData.map(item => item.name),
top: 10
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true // 包含坐标轴刻度标签
},
xAxis: {
type: 'category',
data: this.xAxisData // X轴数据通过prop传入
},
yAxis: {
type: 'value',
name: '金额(元)',
axisLabel: {
formatter: '{value}' // 格式化Y轴标签
}
},
series: this.seriesData.map(item => ({
...item,
type: 'bar' // 固定为柱状图类型
}))
};
this.chartInstance.setOption(option);
}
}
};
</script>
<style scoped>
.bar-chart {
width: 100%;
min-width: 600px;
}
.chart-container {
width: 100%;
height: 400px; /* 固定高度,可根据需求调整 */
}
</style>