I use echarts in my nuxt project, I first tried vue-echarts, but there were some problems. I didn't use nuxt-echarts, and finally I used echarts directly. Below is the usage, vue projects can also refer to. Only for vue3.
Basic Usage of On-demand Import
Create a separate file, I created composables/echarts.js in Nuxt with the following content:
import * as echarts from "echarts/core";
// import echarts necessary components
import {
TitleComponent,
TooltipComponent,
GridComponent,
// DatasetComponent,
// TransformComponent,
LegendComponent
} from "echarts/components";
import { LabelLayout, UniversalTransition } from "echarts/features";
// import Canvas Renderer, note that CanvasRenderer or SVGRenderer is required
import { CanvasRenderer } from "echarts/renderers";
// register necessary components
echarts.use([
TitleComponent,
TooltipComponent,
GridComponent,
LegendComponent,
LabelLayout,
UniversalTransition,
CanvasRenderer
]);
export { echarts };
export function useEcharts(elementRef, options) {
const chart = ref(null);
// resize chart
const resizeChart = () => {
chart.value?.resize();
};
// clean up resources
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);
}
});
watch(() => [chart.value, options.value], () => {
if (!chart.value || !options.value) return;
chart.value.setOption(options.value);
})
onMounted(() => {
window.addEventListener("resize", resizeChart);
});
onUnmounted(dispose);
return {
chart,
};
}
Usage Example
<ClientOnly>
<div ref="chartEl" style="height: 400px"></div>
</ClientOnly>
import { use } from 'echarts/core'
import { LineChart } from "echarts/charts"
use([LineChart])
const chartEl = ref()
const chartOptions = computed(() => {
return {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}
]
}
})
useEcharts(chartEl, chartOptions)
- Chart auto-updates when HTML element is ready and chartOptions change
- When window size changes, chart will resize automatically
- chartEl container must have defined height (fixed or via parent flex layout)
- ClientOnly is Nuxt component (Vue projects can ignore). In nuxt, it is recommended to use this way. Refer to: Issues Encountered When Using Echarts in Vue3.
- Remember to register specific chart types like LineChart
- chartOptions should be computed/ref values, not reactive/plain objects