Vue 3 Composition API + D3.js
Isa Ozler
Posted on April 13, 2020
Recently I created a visualization tool that gives an insight into a particular flow. For this, I used the Composition API in combination with D3.js.
There are three functionalities I took into consideration;
- Initial drawing
- Interactivity on the diagram elements
- Updating the information based on the interactions
Initial drawing
Within the new composition API, the initialization of the diagram has to be in the setup() method. This is called after the "beforeCreated" hook and before the created hook.
In the setup hook, we use a method called useDiagram. This is where we organize all the feature code. Thanks to the composition API in Vue 3 we now can reuse most of the controllers we write, like the "useDiagram" and end up with a much cleaner code.
// index.vue
<template>
<svg ref="diagramEl" />
<button @click="redrawDiagram">Update Diagram</button>
</template>
<style lang="scss">
// diagram styles
</style>
<script>
import useDiagram from './useDiagram.js';
export default {
setup() {
const {
drawDiagram,
redrawDiagram,
resizeDiagram
} = useDiagram({ diagramEl });
onMounted(()=>{
window.addEventListener('resize', resizeDiagram);
drawDiagram();
});
onUnmounted(()=>{
window.removeEventListener('resize', resizeDiagram);
});
return {
drawDiagram,
redrawDiagram,
resizeDiagram
}
}
}
</script>
// useDiagram.js
import { select } from 'd3';
import d3Sankey from './d3-sankey-extention';
import { callbackX } from 'extra-utils';
export default function({ diagramEl }) {
const element = diagramEl.value;
const drawDiagram = () => {
const svg = select(element);
// ... usual append, attr, and transform methods
const sankey = d3Sankey();
// ... usual append sankey links, nodes methods
// on the links or nodes you can attach event listeners
// .on('click / mouseenter / ...', d => callbackX)
};
const redrawDiagram = () => {
// update props or the whole diagram based on use-case
};
const resizeDiagram = () => {
// resize the diagram to match viewport props
};
return {
drawDiagram,
redrawDiagram,
resizeDiagram
}
}
That's all. Feel free to comment your thoughts or experiences.
Posted on April 13, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.