DEV Community

Cover image for Binding Data to Charts using Vue Components and D3

Binding Data to Charts using Vue Components and D3

Brian Greig on August 30, 2018

There is nothing more satisfying than making a change and seeing that change propagated through somewhere immediately. Lately, I have been experim...
Collapse
 
denisinvader profile image
Mikhail Panichev

I make charts with d3 in Vue almost every day and here is some of my best practices:

  • Avoid to import whole d3 - it has a very heavy geo module and many unnecessary modules for most cases. Use the following syntax:
const d3 = {
  ...require('d3-scale'),
  ...require('d3-shape'),
};
Enter fullscreen mode Exit fullscreen mode
  • Use jsx, not d3 selections - it's much simpler when you learn it. You also don't have to watch the data updates and write renderLine and updateLine methods, you just write the render function and deal with reactive data and shadow DOM

I would write an article about d3, Vue and jsx, but I have a little experience in writing and bad english

Collapse
 
ignoreintuition profile image
Brian Greig

Definitely agree on the recommendation to pull in only those dependent modules.

Regarding JSX I assume that is easier / harder based on your familiarity with the syntax.

Collapse
 
denisinvader profile image
Mikhail Panichev

You haven't to use JSX, you can use vue templates, but JSX is a little more flexible. The idea is to use

<path
  :d="lineShape(data)"
  stroke="red"
/>

<!-- or d={this.lineShape(this.data)} in jsx -->

Instead of

d3.select(this.$el).append('path')
  .attr('d', this.lineShape(this.data)
  .attr('stroke', 'red')
;

I think html/svg is more readable

Collapse
 
denisinvader profile image
Mikhail Panichev

Oh and of course some features are simpler with d3 selections - animations and transition for example

Collapse
 
ignoreintuition profile image
Brian Greig

Per your suggestion I updated the example to just pull the dependent d3 files.

Collapse
 
amadeot profile image
Amadeo

This is really cool! Glad to see more data visualization options coming into vue!

Collapse
 
ignoreintuition profile image
Brian Greig

Ideally I think this is something that needs to be build up by the community. If folks want to use this component as a framework for building that out I am happy to coordinate it.