vue.js - 使用 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>
解决方案
推荐阅读
- html - 如何在单击另一个图像时更改我的图像按钮?
- javascript - 如何在这一系列承诺中插入 if 语句?(Vue JS)
- python - Python - 为每个元素查找左侧第一个非零元素的索引
- .htaccess - 如何将域重定向到目录 .htaccess
- android - 为手机上的标准下载目录创建文件提供程序,以通过 Intent 发送 PDF 文件
- mysql - MySQL:根据匹配值将数据从一个表更新或复制到另一个表
- android - Lint 错误:`httpclient` 定义的类与 Android 现在提供的类冲突
- python - 用python制作计算器
- kubernetes - Kubernetes:我可以将来自同一个 PV 的不同子路径挂载到同一个容器的不同位置吗?
- jenkins - 多分支管道 Jenkins 创建的无限循环