vue-Chart.js -在我点击addchart按钮后,图表的数量没有增加,但我的数据数量在增加。我已经尝试了很多方法,但我不能修复它,任何人请帮助我修复我的代码谢谢你的帮助我手编程使用vue.js如果有人可以帮助我。
<template>
<div>
<h1>Vue-Chartsjs</h1>
<div class="bar">
<!-- <Bar
id="my-chart-id"
:options="chartOptions"
:data="chartData"
ref="chart"
/> -->
<Bar
id="my-chart-id"
:options="chartOptions"
:data="chartData"
ref="chart"
/>
<div class="buttons">
<button type="button" class="btn btn-success" @click="addchart">
Add Chart
</button>
<button type="button" class="btn btn-danger" @click="delchart">
Delete Chart
</button>
</div>
</div>
<pre>
{{ this.chartData.datasets }}
</pre>
</div>
</template>
<!-- <script>
import { Bar } from "vue-chartjs";
import {
Chart as ChartJS,
Title,
Tooltip,
Legend,
BarElement,
CategoryScale,
LinearScale,
} from "chart.js";
ChartJS.register(
Title,
Tooltip,
Legend,
BarElement,
CategoryScale,
LinearScale
);
export default {
components: { Bar },
data() {
return {
chartData: {
labels: ["January", "February", "March"],
datasets: [
{
label: "Data",
backgroundColor: "rgba(255, 99, 132, 0.5)",
data: [40, 20, 12],
},
],
},
chartOptions: {
responsive: true,
},
};
},
computed: {},
methods: {
addchart() {
this.chartData.datasets.push({
label: "Data",
backgroundColor: "#f87979",
data: [40, 20, 12],
});
},
delchart() {
this.chartData.datasets.pop();
},
},
mounted() {
},
};
</script> -->
<script>
const chartData = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"],
datasets: [
{
label: "Dataset 1",
data: [20, 5, 4, 8, 10, 4, 7],
backgroundColor: "#DB4C77",
},
],
};
import { Bar } from "vue-chartjs";
import {
Chart as ChartJS,
Title,
Tooltip,
Legend,
BarElement,
CategoryScale,
LinearScale,
} from "chart.js";
ChartJS.register(
Title,
Tooltip,
Legend,
BarElement,
CategoryScale,
LinearScale
);
export default {
components: {
Bar,
},
data() {
return {
chartData: chartData,
};
},
methods: {
addchart() {
const newDataChart = {
label: "Dataset 1",
data: [2, 5, 4, 8, 10, 4, 7],
backgroundColor: "#DB4C77",
};
// chartData.datasets.push(newDataChart)
this.chartData.datasets.push(newDataChart);
},
delchart() {
this.chartData.datasets.pop();
},
},
mounted() {
},
};
</script>
<style scoped>
div {
text-align: center;
}
.bar {
width: 70rem;
margin: 2rem auto;
border-radius: 12px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.25);
padding: 2rem;
background: #fff;
}
.buttons button {
margin-top: 1rem;
margin-right: 5px;
}
</style>
谢谢你的回答
1条答案
按热度按时间jm81lzqq1#
显然,你必须重新构建整个
chartData
对象 * 和 *chartData.datasets
数组才能进行更改检测:只重建对象或只重建数组似乎不起作用,它必须两者都是(可能还有你想要更新的所有其他对象)。
看看操场
或者,您可以将
datasets
提取到它自己的属性中,并将chartData
转换为计算值:现在,每当引用的数据值发生变化时,
chartData
就会自动重建。这可能是更好的模式,因为它读起来更清楚,更容易扩展。这是在操场上