Reusable Vue 3 components and selective imports

Build a reusable Vue 3 chart component, handle updates and disposal, and reduce bundle size with 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

components/BaseChart.vue
<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:

views/Sales.vue
<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>
Always call 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:

utils/echarts.js
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:

components/BaseChart.vue
import echarts from '@/utils/echarts.js';
With selective imports, register everything you use. If a chart fails to render or reports a missing module, first check whether the corresponding module is registered in echarts.use().

💡 Common ECharts pitfalls in Vue

ProblemCauseSolution
Chart is invisibleContainer height is 0, or init runs before onMountedSet a height and initialize in onMounted
Page slows downNo dispose on unmountHandle disposal in the wrapper component
Chart layout breaks on resizeNo resize listenerHandle resizing in the wrapper component
Data changes but the chart does notThe option reference is unchanged and watch does not triggerAdd deep: true or return a new object
Large bundleImporting all of echartsUse 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:

  1. Add two BaseChart instances: a bar chart and a pie chart.
  2. Add a button that changes the bar chart data and observe the automatic update.
  3. Update utils/echarts.js to selectively import only the modules these two charts need.
views/Dashboard.vue
<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!