Reputation: 93
I have Chart.js Chart in a Vue component using vue3-chart-v2. Everything works fine untill I want to update the data.
Right now, I am using a watcher to check if the data changes. This works, but updating the chart does not. My idea was to destroy the chart when the data has changed and rerender it with the new data
I have seen some questions on stack using the mixins reactiveData/ reactiveProp but somehow I can not acces them using vue3-chart-v2, I only get an error.
Could someone help me out? This my first question here on stack
My code:
<script>
import { defineComponent } from 'vue';
import { Doughnut } from 'vue3-chart-v2';
export default defineComponent({
name: 'PieChart',
extends: Doughnut,
props: {
carbonData: Object
},
data() {
return {
chartData: {
labels: ['Slabs', 'Columns', 'Foundation', 'Core'],
datasets: [
{
data: [ this.carbonData.slabs, this.carbonData.columns, this.carbonData.foundation, this.carbonData.core ],
backgroundColor: ['#8FBC8F', '#87CEFA', '#CD853F', '#e64e3e'],
borderWidth: 1,
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
legend: {
position: 'right',
}
}
}
},
mounted () {
this.renderPieChart();
},
methods: {
renderPieChart() {
this.renderChart(this.chartData, this.options);
}
},
watch: {
carbonData : {
deep: true,
handler() {
this.state.chartObj.destroy();
this.renderChart(this.chartData, this.chartOptions);
},
}
},
})
</script>
Upvotes: 3
Views: 1538
Reputation: 1
although it's been a few years, I brought a solution that I had a problem with rendering via api in Vue3 and ChartJS (Pie), in which I used Computed and Watch as follows:
const normalizeValueChart = (data) => {
let labels = [];
let datasets = [];
for (const element of data) {
labels.push(element.label);
datasets.push(element.value);
}
return {
labels: [...labels],
datasets: [
{
data: [...datasets]
}
]
};
}
watch(() => vulnerabilityStore.vulnerabilityInfoChart, async (newValue) => {
computedChartDirectlyRelated.value = normalizeValueChart(newValue.directlyRelated);
});
const computedChartDirectlyRelated = computed({
get() {
return chartDirectlyRelated.value ?? { ...defaultValueChart };
},
set(newValue) {
chartDirectlyRelated.value = newValue;
}
});
Hope it helps someone
Upvotes: 0
Reputation: 21
We use a simple method:
v-if="renderChart"
false
in the beginning but when data is loaded change it to true
false
again and after change of data update it to true
once again.It has worked for us for a long time now.
Upvotes: 2