Reusable Vue 3 components and selective imports
🎯 Introduction
So far, every chart has repeated initialization, resizing, and unmount cleanup code, which is easy to forget. Here, you will build a reusable Vue 3 component that renders any chart with one line of markup and use selective imports to reduce bundle size.
🧱 Why create a wrapper?
Using ECharts directly in application components has three drawbacks:
- Repeated code: every chart needs initialization, setOption, and resize listeners.
- Potential memory leaks: forgetting
dispose()on unmount leaves chart instances in memory. - Inconsistent implementations: different patterns across a team increase maintenance costs.
The goal is for application code to supply only option, while the component handles everything else.
🛠 Building the BaseChart component
<template>
<div ref="chartRef" class="chart"></div>
</template>
<script setup>
import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
import * as echarts from 'echarts';
const props = defineProps({
option: {
type: Object,
required: true,
},
});
const chartRef = ref(null);
let chart = null;
const handleResize = () => {
chart && chart.resize();
};
onMounted(() => {
chart = echarts.init(chartRef.value);
chart.setOption(props.option);
window.addEventListener('resize', handleResize);
});
// Update the chart automatically when option changes
watch(
() => props.option,
(newOption) => {
chart && chart.setOption(newOption);
},
{ deep: true }
);
onBeforeUnmount(() => {
window.removeEventListener('resize', handleResize);
chart && chart.dispose();
chart = null;
});
</script>
<style scoped>
.chart {
width: 100%;
height: 400px;
}
</style>
The component handles four tasks: initialization on mount, updates when option changes, resizing with the window, and disposal on unmount.
Using it takes one line of markup:
<template>
<BaseChart :option="option" />
</template>
<script setup>
import { computed } from 'vue';
import BaseChart from '@/components/BaseChart.vue';
const option = computed(() => ({
title: { text: 'Weekly sales' },
tooltip: { trigger: 'axis' },
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
},
yAxis: { type: 'value' },
series: [
{
name: 'Sales',
type: 'bar',
data: [120, 200, 150, 80, 70],
},
],
}));
</script>
dispose(). In particular, charts frequently toggled with v-if can accumulate undisposed instances and slow down the page.🧰 Reducing bundle size with selective imports
import * as echarts from 'echarts' includes all chart types and components, producing a larger bundle. If you only need a few chart types, import them selectively:
import * as echarts from 'echarts/core';
// Import only the chart types you use
import { BarChart, LineChart, PieChart } from 'echarts/charts';
// Import only the components you use
import {
GridComponent,
LegendComponent,
TitleComponent,
TooltipComponent,
} from 'echarts/components';
// Renderer
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([
BarChart,
LineChart,
PieChart,
GridComponent,
LegendComponent,
TitleComponent,
TooltipComponent,
CanvasRenderer,
]);
export default echarts;
Then replace the import in BaseChart.vue with this module:
import echarts from '@/utils/echarts.js';
echarts.use().💡 Common ECharts pitfalls in Vue
| Problem | Cause | Solution |
|---|---|---|
| Chart is invisible | Container height is 0, or init runs before onMounted | Set a height and initialize in onMounted |
| Page slows down | No dispose on unmount | Handle disposal in the wrapper component |
| Chart layout breaks on resize | No resize listener | Handle resizing in the wrapper component |
| Data changes but the chart does not | The option reference is unchanged and watch does not trigger | Add deep: true or return a new object |
| Large bundle | Importing all of echarts | Use selective imports |
❓ Questions and answers
Q1: Why wrap option in computed?
It creates a new option object when its reactive dependencies change. Combined with the component's watcher, this updates the chart automatically without calling setOption in application code.
Q2: Are there existing community wrappers?
Yes, such as vue-echarts, which follows the same general approach. Building a wrapper yourself helps you understand the lifecycle and what other libraries do internally.
Q3: Can I still use echarts.graphic.LinearGradient with selective imports?
Yes. graphic is part of echarts/core and remains available with selective imports.
Q4: How many charts should I put on one page?
There is no hard limit, but every instance consumes memory. A dozen or so is usually manageable, and dashboards commonly use dozens. Reliable disposal is essential.
🧪 Practice
Build a page with two charts using this lesson's BaseChart component:
- Add two
BaseChartinstances: a bar chart and a pie chart. - Add a button that changes the bar chart data and observe the automatic update.
- Update
utils/echarts.jsto selectively import only the modules these two charts need.
<template>
<!-- Write your code here -->
</template>
<script setup>
// Write your code here
</script>
🎉 You have covered the core ECharts skills! From your first chart to reusable components, you now have the tools to build data visualizations in real projects. Put them to work and turn your data into informative charts!
