我在向折线图中动态添加数据时遇到了问题。我计划在用户每次提交包含新数据的表单时都用新数据更新折线图。目前,我可以将新数据推送到App.vue的data函数中的datasets数组中。但图表不会生成新数据。如果我手动将新数据键入数据集数组,它就会工作,这让我更加困惑。我该怎么做才能修好它?
App.vue
<template>
<div>
<form>
<div class="row">
<div class="mb-3 col-6">
<label class="form-label">Score</label>
<input type="number" min="0" max="100" class="form-control" id="score"
name="score" placeholder="Score in %" v-model='score' />
</div>
<div class="mb-3 form-check col-6">
<label class="form-label">Exam Type</label>
<select class="form-select form-select"
aria-label=".form-select-sm example" id="examType"
v-model='examType'>
<option value="CA1">CA1</option>
<option value="SA1">SA1</option>
<option value="CA2">CA2</option>
<option value="SA2">SA2</option>
</select>
</div>
</div>
<div class="row">
<div class="mb-3">
<label class="form-label">Subject</label>
<input type="text" class="form-control" id="subject" name="subject"
placeholder="" v-model='subject' />
</div>
</div>
<div class="modal-footer d-block">
<button type="submit" data-bs-dismiss="modal"
class="btn btn-warning float-end" @click="addResult">Submit</button>
</div>
</form>
<div>
<ChartTest :data="data" :title='title' />
</div>
</div>
</template>
<script>
import ChartTest from "../components/ProgressPage/ChartTest.vue";
export default {
name: "Progress",
components: {
ChartTest
},
data() {
return {
score: '',
examType: '',
subject: '',
existingSubjects: [],
colors: ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850"],
title: '',
data: {
labels: ['CA1', 'SA1', 'CA2', 'SA2'],
datasets: [
//dynamically add data here
]
},
}
},
methods: {
addResult() {
let count = this.existingSubjects.length
if (!this.existingSubjects.includes(this.subject)) {
this.existingSubjects.push(this.subject)
console.log(this.subject)
const newData = {
data: [this.score,54,43],
label: this.subject,
borderColor: this.colors[count],
fill: false
}
this.data.datasets.push(newData)
console.log( this.data.datasets)
} else {
//TBC
}
}
},
}
</script>
ChartTest.vue
<template>
<canvas id="progress-chart" width="600" height="450"></canvas>
</template>
<script>
import Chart from 'chart.js/auto';
export default {
name: 'ChartTest',
props: {
data: Object,
title: String
},
mounted() {
new Chart(document.getElementById("progress-chart"), {
type: 'line',
data: this.data,
options: {
plugins: {
title: {
display: true,
text: this.title
}
},
scales: {
y: {
display: true,
stacked: true,
max: 0,
min: 100,
title: {
display: true,
text: 'Your Score (%)'
}
}
}
}
});
}
}
</script>
1条答案
按热度按时间4jb9z9bj1#
我认为这里比较合理的解决方案是在ChartTest组件中观察属性的变化,首先创建图表示例
(const chart = new Chart(....))
,每次图表数据发生变化时,都要调用chart.update()
来更新图表。跟随this thread了解如何观察道具变化。