DEV Community

Cover image for Vue 3 Composition API + D3.js
Isa Ozler
Isa Ozler

Posted on • Updated on

Vue 3 Composition API + D3.js

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;

  1. Initial drawing
  2. Interactivity on the diagram elements
  3. 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.

Discussion (2)

Collapse
julio_bastidabernal_141c profile image
Julio Bastida Bernal

This is awesome! Do you have a working sample where I could see this in action?

Collapse
isaozler profile image
Isa Ozler Author

Thx Julio, this was a while ago, don't have a sample publicly available somewhere but, maybe you can try the code given above, if you get stuck I can try to help