我有以下使用ChartJS的Vue模板
<template>
<div class="chart">
<div>
<canvas ref="cpu"> </canvas>
</div>
<div>
<canvas ref="memory"> </canvas>
</div>
</template>
<script>
import Chart from "./deps/Chart.bundle";
...
let ChartOptions = {
scales: {
xAxes: [{
stacked: true,
type: 'time',
time: {
unit: 'hour'
}
}],
yAxes: [{
ticks: {
max: 45
},
stacked: true
}]
}
};
let ChartConfig =
{
type: 'scatter',
data: {
datasets: []
},
options: ChartOptions
};
export default {
this.cpuChart = new Chart(this.$refs.cpu.getContext('2d'), ChartConfig);
this.memoryChart = new Chart(this.$refs.memory.getContext('2d'), ChartConfig);
...
observable.subscribe(=>{
let cpu = col1.map(item=>{
return {
server: item.server,
t: item.time,
y: item.cpu
}
});
let memory = col1.map(item=>{
return {
server: item.server,
t: item.time,
y: item.memory
}
});
servers.forEach(server=>{
this.cpuChart.data.datasets.push({
label: server.name,
backgroundColor: dynamicColors(),
showLine: true,
data: cpu.filter(item =>{
return item.server === server.serverAddress
})
});
this.memoryChart.data.datasets.push({
label: server.name,
backgroundColor: dynamicColors(),
showLine: true,
data: memory.filter(item =>{
return item.server === server.serverAddress
})
});
});
this.cpuChart.update();
this.memoryChart.update();
});
}
问题在于,当我运行这个时,内存和cpu都被添加到cpuChart中,并且没有任何内容被添加到内存中。我想要发生的是拥有两个完全独立的图表(每种类型一个)。我可以使用ChartJS同时获得2张图表吗?
答案 0 :(得分:0)
看起来我需要为每个图表创建两个单独的实例,所以我需要...
let ChartConfig = {
type: 'scatter',
data: {
datasets: []
},
options: ChartOptions
};
let ChartConfig2 = {
type: 'scatter',
data: {
datasets: []
},
options: ChartOptions
};
...
this.cpuChart = new Chart(this.$refs.cpu.getContext('2d'), ChartConfig);
this.memoryChart = new Chart(this.$refs.memory.getContext('2d'), ChartConfig2);
我有点明白为什么,但对我来说仍然感觉有点笨拙。