How should I refer to the chart in a vue chart instance and destroy it? I've tried:
var chartVue = new Vue({
el: '#chart',
extends: VueChartJs.Line,
data: {
chartData: {...},
options: {...}
},
mounted() {
this.renderMyChart()
},
methods: {
renderMyChart: function() {
this.renderChart(
this.chartData,
this.options
);
}
},
watch: {
chartData: function() {
this._chart.destroy();
this.renderMyChart();
}
}
});
But it complains
TypeError: Cannot read property 'destroy' of undefined
So it seems this._chart
is not the right way to refer to the current chart, anybody knows what is the right way to do this? The idea comes from this stack overflow answer.
The Chart
object accessible via this._chart
is not set until after the renderChart
method is called. What's most likely happening is that your chartData
is somehow being updated before that renderChart
method has been called. So, the watcher for chartData
is referencing this._chart
before it has been defined.
However, vue-chartjs
has a baked-in way to re-render the chart when the dependant data change: the reactiveData
and reactiveProp
mixins. By adding either of these mixins, the changes to the chartData
(data-property or prop, respectively) will re-render the chart to reflect the updated data.
You should use the reactiveData
mixin instead:
var chartVue = new Vue({
el: '#chart',
extends: VueChartJs.Line,
mixins: [ VueChartJS.mixins.reactiveData ],
data() {
return {
chartData: {...},
options: {...}
}
},
mounted() {
this.renderChart(this.chartData, this.options);
},
});