<script lang="ts" setup>
|
import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
|
import * as echarts from 'echarts';
|
import { debounce } from 'lodash-es';
|
import { storeToRefs } from 'pinia';
|
|
import { useJnpfUniverStore } from '../../../store';
|
|
interface Data {
|
id: string;
|
piniaStoreId: string;
|
}
|
interface PropsType {
|
data: Data;
|
}
|
|
defineOptions({ name: 'JnpfUniverFloatEchart' });
|
|
const props = defineProps<PropsType>();
|
|
const floatChartContainerRef = ref<HTMLDivElement | null>(null);
|
|
const jnpfUniverStore = useJnpfUniverStore(props?.data?.piniaStoreId);
|
const { focusedFloatEchartDataCache } = storeToRefs(jnpfUniverStore);
|
|
let floatChartInstance: echarts.ECharts | null = null;
|
let resizeObserver: null | ResizeObserver = null;
|
|
// 处理窗口大小变化的函数,带300ms 防抖
|
const handleResize = debounce(() => {
|
floatChartInstance?.resize();
|
}, 300);
|
|
// 初始化或更新图表
|
function initialize(option: echarts.EChartsOption) {
|
if (!floatChartContainerRef.value) {
|
return;
|
}
|
|
if (!floatChartInstance) {
|
floatChartInstance = echarts?.init(floatChartContainerRef.value);
|
}
|
|
floatChartInstance?.clear();
|
|
// 使用传入的 options 配置图表
|
floatChartInstance?.setOption(option);
|
|
// 设置 ResizeObserver 监听容器大小变化
|
if (!resizeObserver) {
|
resizeObserver = new ResizeObserver(handleResize);
|
resizeObserver?.observe(floatChartContainerRef.value);
|
}
|
}
|
|
onMounted(() => {
|
const { id: domId, piniaStoreId } = props.data ?? {};
|
|
if (!floatChartContainerRef.value || !domId || !piniaStoreId) {
|
return;
|
}
|
|
const floatEchartDataCaches = jnpfUniverStore?.floatEchartDataCaches ?? {};
|
|
const targetOption = Object.values(floatEchartDataCaches as Record<string, { domId: string; option: any }>)?.find(item => item?.domId === domId)?.option;
|
initialize(targetOption);
|
});
|
|
// 销毁
|
onBeforeUnmount(() => {
|
if (resizeObserver && floatChartContainerRef.value) {
|
resizeObserver?.unobserve(floatChartContainerRef.value);
|
}
|
|
resizeObserver?.disconnect();
|
floatChartInstance?.dispose();
|
});
|
|
watch(
|
() => focusedFloatEchartDataCache.value,
|
value => {
|
const { domId, drawingId, option } = value;
|
|
if (!domId && !drawingId) {
|
// store置空的情况下,不响应
|
return;
|
}
|
|
const containerId = floatChartContainerRef.value?.getAttribute('id');
|
if (domId !== containerId) {
|
return;
|
}
|
|
initialize(option);
|
},
|
);
|
</script>
|
|
<template>
|
<div ref="floatChartContainerRef" :id="data.id" class="jnpf-univer-float-echart-ele"></div>
|
</template>
|
|
<style lang="scss" scoped>
|
.jnpf-univer-float-echart-ele {
|
position: absolute;
|
width: 100%;
|
height: 100%;
|
background: #f9f9f9;
|
}
|
</style>
|