我想有多个vue-chart.js图形,每个刷新(添加一个新的数据点)每5s。值来自传感器,并通过道具传递(我正在为节点红色应用程序编写UI,我认为这与问题无关)。
我设法得到一个图形完美地工作,但如果我放置2个图形,传递的值同时显示在两个图形中(不只是在一个,应该显示它们)。
看到自己在这里工作CodeSandBox演示
令我困惑的是,adddata
中的console.log(this.myChart)
显示"正确"。图(不同id
,不同context
)。我想我已经创建了单独的图形实例,但我仍然不能只向其中一个添加数据。
我不经常使用value,我可能会错过一些重要的东西。谢谢你!
组件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>
chartSetting
对象对于所有组件实例都是相同的,因为它在组件模块求值时被定义一次。
data
是工厂函数的原因是它为每个实例返回一个新的数据对象,该对象在实例之间不共享。
应该是:
data() {
const chartSetting = ...
return {
myChart: null,
chartSetting: chartSetting,
};
}