I am looking to implement multiple vue-chart.js graphs, each refreshing (adding a new data point) every 5 seconds. The data comes from a sensor and is passed using props (I am developing the UI for a node-red application, but this detail may not be relevant to the issue at hand).
While I successfully got one graph working correctly, I encountered an issue when trying to display values in two separate graphs simultaneously. Instead of each graph displaying its respective values, both graphs were updating with the same values.
You can see the issue demonstrated here.
What confuses me is that when I log this.myChart
in the adddata
method, it shows the "correct" graph (with different id
and context
). Even though I believe I have created individual instances of the graphs, I cannot seem to add data to only one of the graphs.
Since I do not use Vue frequently, I might be overlooking something important. Any insights would be greatly appreciated!
Component Test.vue
<template>
<div>
<canvas :id="name"></canvas>
</div>
</template>
<script>
import Chart from "chart.js";
const chartSetting = {
type: "line",
data: {
datasets: [
{
label: "setpoint",
data: [],
borderColor: "blue",
borderWidth: 3,
},
],
},
options: {},
};
let interval;
export default {
name: "test",
data() {
return {
myChart: null,
chartSetting: chartSetting,
};
},
props: ["id", "name", "setpoint"],
methods: {
adddata(setpoint, time) {
this.myChart.data.datasets[0].data.push(setpoint);
this.myChart.data.labels.push(time);
this.myChart.update();
console.log(`now printing ${setpoint} to this graph:`);
console.log(this.myChart);
},
createChart(chartId, chardData) {
const ctx = document.getElementById(chartId);
// Save reference
this.myChart = new Chart(ctx, {
type: chardData.type,
data: chardData.data,
options: chardData.options,
});
interval = setInterval(() => {
let date = new Date();
let seconds = date.getSeconds();
this.adddata(this.setpoint, seconds);
}, 5000);
},
},
mounted() {
this.createChart(this.name, this.chartSetting);
},
};
</script>
App.vue
<template>
<div id="app">
<p>
graphs get new data from 2 different sensors every 5 seconds. Here
simulated as "6" and "3"
</p>
<h3>this graph should only show 6</h3>
<test name="grap1" id="1" setpoint="6" />
<h3>this graph should only show 3</h3>
<test name="grap2" id="2" setpoint="3" />
</div>
</template>
<script>
import Test from "./components/Test";
export default {
name: "App",
components: {
Test,
},
};
</script>