Build a reusable Vue 3 component
🎯 Introduction
So far, D3 code has lived directly in page components. Copying scales, axes, and event listeners for every chart is repetitive and hard to maintain. This article defines clear responsibilities for D3 and Vue, wraps a chart in a reusable Vue 3 component, and covers data updates and unmount cleanup so you can use these skills in a project.
🧱 Divide responsibilities between D3 and Vue
Both D3 and Vue manipulate the DOM. If they manage the same elements, their updates can conflict. Here is an example of what to avoid:
<template>
<!-- Vue renders the bars with v-for -->
<svg>
<rect v-for="d in list" :key="d.day" :height="d.value" />
</svg>
</template>
<script setup>
// D3 also modifies the same bars
d3.selectAll('rect').attr('fill', 'red');
</script>
On its next update, Vue can overwrite D3's changes using its virtual DOM. It also does not know about elements D3 removes. These competing updates can leave the chart inconsistent.
A common approach is:
Let Vue render an empty container and let D3 manage all graphics inside it.
Follow three rules:
- Put only an empty
<svg>with arefin the template, withoutv-for. - Let D3 create and update the container's
rect,path, and other graphic elements. - Initialize D3 in
onMounted, once the container exists.
🛠 Build a BarChart component
Following that approach, encapsulate scales, axes, and data binding in a component that exposes a single data prop:
<template>
<svg ref="svgRef" class="chart"></svg>
</template>
<script setup>
import { onMounted, ref, watch } from 'vue';
import * as d3 from 'd3';
const props = defineProps({
data: {
type: Array,
required: true,
},
});
const svgRef = ref(null);
const render = () => {
const margin = { top: 20, right: 20, bottom: 30, left: 40 };
const width = 480 - margin.left - margin.right;
const height = 280 - margin.top - margin.bottom;
// Clear before redrawing to prevent duplicate graphics
const root = d3.select(svgRef.value);
root.selectAll('*').remove();
const svg = root.append('g').attr('transform', `translate(${margin.left}, ${margin.top})`);
const xScale = d3
.scaleBand()
.domain(props.data.map(d => d.day))
.range([0, width])
.padding(0.2);
const yScale = d3
.scaleLinear()
.domain([0, d3.max(props.data, d => d.value)])
.range([height, 0])
.nice();
svg.selectAll('rect')
.data(props.data)
.join('rect')
.attr('x', d => xScale(d.day))
.attr('y', d => yScale(d.value))
.attr('width', xScale.bandwidth())
.attr('height', d => height - yScale(d.value))
.attr('fill', '#5470c6');
svg.append('g').attr('transform', `translate(0, ${height})`).call(d3.axisBottom(xScale));
svg.append('g').call(d3.axisLeft(yScale));
};
onMounted(render); // Draw for the first time after mounting
// Redraw automatically when data changes
watch(() => props.data, render, { deep: true });
</script>
<style scoped>
.chart {
width: 480px;
height: 280px;
}
</style>
The component has four parts:
definePropsdeclares thedataprop.rendercontains the complete drawing logic from the preceding articles.onMounted(render)draws the initial chart after mounting.watchredraws when data changes;deep: truealso detects changes inside the array.
Using it takes one line in the template:
<template>
<BarChart :data="list" />
</template>
<script setup>
import { ref } from 'vue';
import BarChart from '@/components/BarChart.vue';
const list = ref([
{ day: 'Mon', value: 120 },
{ day: 'Tue', value: 200 },
{ day: 'Wed', value: 150 },
]);
</script>
render uses a straightforward clear-and-redraw strategy: selectAll('*').remove() removes the graphics before recreating them. This is simple, reliable, and fast enough for many use cases. For smooth animations, replace it with incremental data joins and transitions from the transitions article.Here is a complete demonstration of this component approach, including growing bars on entry, transitions on refresh, and hover tooltips:
💡 Common pitfalls when using D3 with Vue
| Problem | Cause | Solution |
|---|---|---|
| No graphics appear | Initialization before onMounted, when the container does not exist | Draw inside onMounted |
| Data changes but the chart does not | No watcher for prop changes | Use watch and redraw in its callback |
| Graphics accumulate and overlap | Old graphics were not cleared | Call selectAll('*').remove() before redrawing |
| Inconsistent rendering | Vue and D3 modify the same nodes | Keep the template container empty and let D3 manage its contents |
| Errors after unmounting | Window event listeners remain registered | Remove listeners in onBeforeUnmount |
Unlike ECharts, D3 has no dispose method. Vue removes the component's DOM on unmount, so DOM cleanup generally needs no extra work. Remember to remove any listeners you registered on window or document, such as resize listeners, in onBeforeUnmount.
❓ Questions and answers
Q1: What if the parent fetches data asynchronously and starts with an empty array?
Add a guard at the start of render: if (!props.data.length) return;. The watcher redraws when the data arrives.
Q2: Will multiple BarChart instances on one page interfere with one another?
No. Each instance has its own svgRef, and D3 selections are scoped to that container, keeping instances isolated.
Q3: Why use D3 instead of rendering bars with v-for?
For simple static charts, v-for can work. D3 provides a coordinated set of scales, axes, transitions, and zoom behaviors; v-for only handles rendering the elements.
Q4: Are there existing D3 and Vue wrapper libraries?
Yes, but D3's strength is full customization, so projects often build their own components as shown here. Understanding the underlying approach makes those libraries easier to evaluate.
🧪 Exercise
Build a data dashboard using this article's BarChart:
- Add a
BarChartand a “Refresh data” button to the page. - On click, generate five random data items, assign them to
list, and observe the automatic redraw. - As an extension, replace clear-and-redraw with data joins and transitions so bars change height smoothly.
<template>
<!-- Write your code here -->
</template>
<script setup>
// Write your code here
</script>
🎉 You have covered D3's core skills: data binding, scales, axes, shape generators, transitions, interactions, and Vue 3 component integration. You can now build custom visualizations with D3. There is much more to explore, including force-directed graphs, maps, and tree diagrams!
