When using Echarts in Nuxt, I encountered the error: [ECharts] Can't get DOM width or height. Please check dom.clientWidth and dom.clientHeight. They should not be 0.
Basic Usage
Create composables/useECharts.ts
. This code automatically listens for window resize events.
import * as echarts from "echarts";
export function useECharts(elementRef: Ref<HTMLElement | null>) {
const chart = ref<echarts.ECharts | null>(null);
// Initialize chart
const initChart = () => {
if (!elementRef.value) return;
chart.value = echarts.init(elementRef.value);
// Auto resize when window changes
window.addEventListener("resize", resizeChart);
};
// Resize handler
const resizeChart = () => {
chart.value?.resize();
};
// Cleanup
const dispose = () => {
window.removeEventListener("resize", resizeChart);
if (chart.value) {
chart.value.dispose();
chart.value = null;
}
};
watch(elementRef, () => {
if (elementRef.value) {
chart.value = echarts.init(elementRef.value);
}
});
onMounted(() => {
window.addEventListener("resize", resizeChart);
});
onUnmounted(dispose);
return {
chart,
};
}
Usage example:
<template>
<div>
<div ref="chartEl" />
</div>
</template>
<script lang="ts" setup>
const chartEl = ref<HTMLElement | null>(null);
const {chart} = useECharts(chartEl)
const chartData = computed(() => {
return {
// chart options
};
});
watch(() => [chart.value,chartData.value],() => {
if(!chart.value ||!chartData.value) return;
chart.value.setOption(chartData.value);
})
</script>
Issues Encountered
Blank Chart Area
The chart area appears blank with a browser console warning: ECharts Can't get DOM width or height. Please check dom.clientWidth and dom.clientHeight. They should not be 0.
Echarts requires the target element to have non-zero width and height. Width is usually fine, but height defaults to 0 when empty. Solutions include setting fixed height or using flex layout.
Even after setting height, the issue persisted. Trying Vue's nextTick didn't help. The final solution was wrapping the echarts element with Nuxt's client-only component. I suspect this is Nuxt-specific.
<client-only>
<div ref="chartEl"></div>
</client-only>
Usage in v-for
Using the above code inside v-for makes chartEl.value an array instead of a single element. It's recommended to place the chart element outside v-for .