[Vuejs]-Vue-Chart.js – When I add data, charts are not updated

0👍

Apparently you have to rebuild the whole chartData object and the chartData.datasets array for change detection to work:

addchart() {
  const newSet = ...
  this.chartData = {...this.chartData, datasets: [...this.chartData.datasets, newSet]}
  }
},

Rebuilding only the object or only the array does not seem to work, it has to be both (and probably every other object you want to update).

Have a look at the playground


Alternatively, you can extract datasets into its own property and turn chartData into a computed value:

  data() {
    return {
      datasets: [...],
  },
  computed:{
    chartData(){
      return {
        labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"],
        datasets: [...this.datasets],
      }
    }
  },

Now chartData is automatically rebuild whenever a referenced data value changes. This is probably the better pattern, as it reads more clearly and is easier to extend.

Here it is in a playground

Leave a comment