How can i zoom a chart with D3 in vuejs?

Viewed 241

I'm trying to do a zoom in my chart with d3.

I have in my methods :

  this.chart = d3.select("#chart")
    .append("g")
    .attr("transform", `translate(${margin.left}, ${margin.top})`);

  this.x = d3.scaleLinear()
    .range([0, width - margin.left - margin.right]);

  this.y = d3.scaleLinear()
    .range([height - margin.top - margin.bottom, 0]);

  this.xAxis = this.chart.append("g")
    .attr(
      "transform",
      `translate(0, ${height - margin.top - margin.bottom})`
  );

And in my template :

<div id="app">
  <svg id="chart" viewBox="0 0 500 500"></svg>
</div>

So basically, i tried this :

testZoom() {
  this.chart.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")")
},
this.chart = d3.select("#chart")
  .call(d3.behavior.zoom().on("zoom", this.testZoom))
  .append("g")
  .attr("transform", `translate(${margin.left}, ${margin.top})`);

And a lot of other things, but i have everytime this error

[Vue warn]: Error in mounted hook: "TypeError: d3__WEBPACK_IMPORTED_MODULE_0__.behavior is undefined"

I was wondering if anyone had any idea why this isn’t working, and what can I do to solve my problem.

1 Answers

To fix the error, we can do like this

this.chart = d3.select("#chart")
   .call(d3.zoom().on("zoom", this.test2))
   .append("g")
   .attr("transform", `translate(${margin.left}, ${margin.top})`)

test2(d) {
  this.chart.attr("transform", d.transform)
},

The problem was because i'm using D3 V6. With theV5, d3.event.translate will work (response by Michael Rovinsky)

Related