Files
yudao-dev/src/views/home/components/coresBar.vue

132 lines
3.8 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<div ref="cockpitEffChip" id="coreLineChart" style="height: 184px; width: 100%;"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
name: 'Container',
components: {},
// 接收父组件传递的 series 数据
props: {
chartSeries: {
type: Object,
default: () => {{}} // 默认空数组,避免报错
},
xAxisData: {
type: Array,
default: () => [] // 默认空数组,避免报错
},
dateData: {
type: Object,
default: () => {} // 默认空数组,避免报错
},
},
data() {
return {
myChart: null, // 存储图表实例,方便后续操作
resizeHandler: null // 窗口resize事件处理器
};
},
mounted() {
this.$nextTick(() => {
this.initData();
});
// 注册窗口resize事件使用稳定的引用以便后续移除
this.resizeHandler = () => {
if (this.myChart) {
this.myChart.resize();
}
};
window.addEventListener('resize', this.resizeHandler);
},
watch: {
// 监听 series 数据变化,实时更新图表
chartSeries: {
handler() {
this.updateChart();
},
deep: true // 深度监听数组内元素变化
}
},
methods: {
initData() {
const chartDom = this.$refs.cockpitEffChip;
if (!chartDom) {
console.error('图表容器未找到!');
return;
}
this.myChart = echarts.init(chartDom);
this.updateChart(); // 初始化时渲染图表
},
// 单独提取更新图表的方法,方便复用
updateChart() {
if (!this.myChart) return;
const option = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
label: { backgroundColor: '#6a7985' }
}
},
grid: { top: 35, bottom: 3, right: 15, left: 18, containLabel: true},
xAxis: [
{
type: 'category',
boundaryGap: false,
axisTick: { show: false },
axisLine: {
show: true,
onZero: false,
lineStyle: { color: 'rgba(0, 0, 0, 0.15)' }
},
axisLabel: {
color: 'rgba(0, 0, 0, 0.45)',
fontSize: 12,
interval: 0,
// width: 38,
overflow: 'break',
formatter: (value) => {
const dateParts = value.split('-'); // ["2025", "07", "01"]
if (dateParts.length < 2) return value;
// 去掉月份前面的0然后加上"月"
const month = dateParts[1].replace(/^0+/, '');
return `${month}`;
}
},
data: this.xAxisData
}
],
yAxis: {
name: this.chartSeries.unit,
nameTextStyle: { color: 'rgba(0, 0, 0, 0.45)', fontSize: 14, align: 'right' },
axisTick: { show: false },
axisLabel: { color: 'rgba(0, 0, 0, 0.45)', fontSize: 12 },
splitLine: { lineStyle: { color: 'rgba(0, 0, 0, 0.15)' } },
axisLine: { show: true, lineStyle: { color: 'rgba(0, 0, 0, 0.15)' } }
},
series: this.chartSeries.series // 使用父组件传递的 series 数据
};
this.myChart.setOption(option, true); // 第二个参数 true 表示替换现有配置
}
},
beforeDestroy() {
// 移除窗口resize事件监听器
if (this.resizeHandler) {
window.removeEventListener('resize', this.resizeHandler);
this.resizeHandler = null;
}
// 销毁图表,避免内存泄漏
if (this.myChart) {
this.myChart.dispose();
this.myChart = null;
}
}
};
</script>