Chartjs-Update data when pressing submit in chartjs in vuejs

1๐Ÿ‘

โœ…

I fixed it successfully.In this way : v-if="loaded"

<b-card-body>
    <chartjs-component-line-chart
      v-if="loaded"
      :height="400"
      :data="data"
      :options="options"
      :plugins="plugins"
    />
  </b-card-body>

data() {
  return: {
     data: {
        loaded: false,
        labels: [],
        datasets: [
          {
            data: [70, 95, 100, 120, 257, 271, 300, 321, 383, 450],
            label: "Supper",
            borderColor: "#3e95cd",
          },
        ],
      },
      options: {
        title: {
          display: true,
          text: "Report",
        },
        responsive: true,
        maintainAspectRatio: false,
      },
  }
},
created() {
    this.data.labels = [1980, 1985, 1990, 1995, 2000, 2005, 2010, 2015, 2020, 2025];
    this.loaded = true;
  },
methods: {
   submitData() {
     this.data.labels = [1985, 1990, 1995, 2000, 2005, 2010, 2015, 2020, 2025, 2030];
     this.loaded = true;
  }
}

1๐Ÿ‘

Chart.js itself is not reactive, you need to call the update method yourself when the data is changed. This behaviour of being non reactive out of the box is being taken over by vue-chartjs.

To make it reactive you need to add the reactiveProp mixin to your lineChart component according to the docs.

import { Line, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins

export default {
  extends: Line,
  mixins: [reactiveProp],
  props: ['options'],
  mounted () {
    // this.chartData is created in the mixin.
    // If you want to pass options please create a local options object
    this.renderChart(this.chartData, this.options)
  }
}

You can also implement your own watcher and call the update method of chart.js yourself according to the docs

watch: {
  data () {
    this.$data._chart.update()
  }
}

Leave a comment