fix: 修复部分场景 echarts 在使用 v-show 时获取不到 width 的问题 (#6776)

This commit is contained in:
vent 2025-09-30 05:09:33 +08:00 committed by GitHub
parent 81bb7456f8
commit 1e029dbc9a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -32,6 +32,21 @@ function useEcharts(chartRef: Ref<EchartsUIType>) {
const { height, width } = useWindowSize(); const { height, width } = useWindowSize();
const resizeHandler: () => void = useDebounceFn(resize, 200); const resizeHandler: () => void = useDebounceFn(resize, 200);
const getChartEl = (): HTMLElement | null => {
const refValue = chartRef?.value as unknown;
if (!refValue) return null;
if (refValue instanceof HTMLElement) {
return refValue;
}
const maybeComponent = refValue as { $el?: HTMLElement };
return maybeComponent.$el ?? null;
};
const isElHidden = (el: HTMLElement | null): boolean => {
if (!el) return true;
return el.offsetHeight === 0 || el.offsetWidth === 0;
};
const getOptions = computed((): EChartsOption => { const getOptions = computed((): EChartsOption => {
if (!isDark.value) { if (!isDark.value) {
return {}; return {};
@ -54,7 +69,7 @@ function useEcharts(chartRef: Ref<EchartsUIType>) {
const renderEcharts = ( const renderEcharts = (
options: EChartsOption, options: EChartsOption,
clear = true, clear = true
): Promise<Nullable<echarts.ECharts>> => { ): Promise<Nullable<echarts.ECharts>> => {
cacheOptions = options; cacheOptions = options;
const currentOptions = { const currentOptions = {
@ -69,6 +84,13 @@ function useEcharts(chartRef: Ref<EchartsUIType>) {
return; return;
} }
nextTick(() => { nextTick(() => {
const el = getChartEl();
if (isElHidden(el)) {
useTimeoutFn(async () => {
resolve(await renderEcharts(currentOptions));
}, 30);
return;
}
useTimeoutFn(() => { useTimeoutFn(() => {
if (!chartInstance) { if (!chartInstance) {
const instance = initCharts(); const instance = initCharts();
@ -83,6 +105,10 @@ function useEcharts(chartRef: Ref<EchartsUIType>) {
}; };
function resize() { function resize() {
const el = getChartEl();
if (isElHidden(el)) {
return;
}
chartInstance?.resize({ chartInstance?.resize({
animation: { animation: {
duration: 300, duration: 300,