[英]How to dynamically update data in chart.js
How to update the data to the chart that I define when I mount?如何将数据更新到我挂载时定义的图表?
I think that I fail to properly reference the chart?我认为我没有正确参考图表?
It is the data() function that fails, with "Could not find linechart", but how do I specify linechart?失败的是 data() 函数,显示“找不到折线图”,但是如何指定折线图?
I have made this code sandbox我已经制作了这个代码沙箱
<template>
<div class="container center">
<div class="px-3">
<label for="Product">Select a:</label>
<select
class="border-solid border-2 rounded-md p-1 font-bold"
v-on:input="outputData()"
id="Product"
aria-placeholder="Product"
>
<option value="" disabled selected>Product</option>
<option>1</option>
</select>
</div>
<div>
<canvas id="line-chart"></canvas>
</div>
</div>
</template>
<script>
import Chart from "chart.js/auto";
export default {
name: "line-plot",
mounted() {
const ctx = document.getElementById("line-chart");
const linechart = new Chart(ctx, this.chartData);
return linechart;
},
data() {
return {
chartData: {
type: "line",
data: {
labels: ["a", "b", "c"],
datasets: [
{
label: "Contract",
data: [5, 5, 5],
borderColor: "#9B202A",
borderWidth: 3,
},
{
label: "FWD",
data: [5, 10, 15],
borderColor: "#6F6F6F",
borderWidth: 3,
},
],
},
},
options: [],
};
},
methods: {
outputData() {
const contractPrice = {
label: "Contract",
data: [6, 6, 6],
borderColor: "#9B202A",
borderWidth: 3,
};
const fwdPrice = {
label: "FWD",
data: [10, 10, 10],
borderColor: "#6F6F6F",
borderWidth: 3,
};
const labels = ["a", "b", "c"];
this.chartData.data.labels = labels;
this.chartData.data.datasets[0] = contractPrice;
this.chartData.data.datasets[1] = fwdPrice;
linechart.update();
},
},
};
</script>
<style>
.center {
margin: auto;
}
</style>
You should define your variable to hold the Chart
outside the mounted
function in order to be visible to the other methods.您应该定义变量以将
Chart
保存在已mounted
函数之外,以便其他方法可见。
So instead use this所以改为使用这个
let linechart;
export default {
name: "line-plot",
mounted() {
const ctx = document.getElementById("line-chart");
linechart = new Chart(ctx, this.chartData);
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.