首页 > 解决方案 > 使用 Vue 更新 d3 图表以更改数据

问题描述

这是我第一次在这里提出问题,所以我希望我能用有意义的方式来表达它。

我刚刚开始学习 Vue 和 D3,我正在制作一个基于一些用户数据生成条形图的应用程序。它应该显示一个代表一个用户的图表,然后有一个按钮列表,您可以单击这些按钮来生成代表每个其他用户的图表。现在,它可以为每组不同的数据生成一个图表,但我不知道如何在选择新用户时更新图表。

单击按钮时,图表顶部 H2 标题中的名称会更新,因此我知道我的“featuredUser”道具正在更改,因此带有用户名的按钮似乎正在工作(它们位于另一个组件中):

<template>
  <div id="Chart">
  <h2>{{ featuredUser.firstName }} {{ featuredUser.lastName }}</h2>
       <div class="Chart"></div>
</div>

</template>

<script>
import * as d3 from 'd3';

export default {
 
props: ["featuredUser"],
name: "Chart",

  watch: {
    featuredUser() { 
      this.generateChart();
      // the below console log works, even when the chart doesn't update
      // so it seems that this varaible is being watched for changes
      console.log(this.featuredUser.firstName);
    }
  },

  methods: {
    generateChart() {
      let qualities = this.featuredUser.qualities;

// EDIT: Adding the following two lines solves the problem
// the remove the previous chart before the new one is generated
   d3.select(".Chart")
        .selectAll('div').remove();

      d3.select(".Chart")
        .selectAll('div')
        .data(qualities)
        .enter().append('div')
        .style('width', function (d) { return (d.score * 5)+10 + "em"})
        .text(function (d) { return d.quality })
        .attr("id", function(d) {return d.type}); 
    },
  },

// having the below as 'setup()' allows the chart to be generated on click
// for one user but it doesn't change when another user is clicked, 
// having it set as 'mounted()' generates the chart of the chosen user on load,
// but it will not change again.

  setup() {
    this.generateChart();
  }
};

</script>

标签: vue.jsd3.jsreactive

解决方案


推荐阅读