Search code examples
vue.jschart.jsvue-chartjs

vue-chartjs how to load data


Linechart.js

import { Line } from 'vue-chartjs'

export default {
  extends: Line,
  props:['chart']
    mounted () {
      this.renderChart({
        labels: ['1','2','3','4','5','6','7'],
        datasets: [
          {
            label: 'Data One',
            backgroundColor: '#F64A32',
            data: this.chart
          }
        ]
      }, {responsive: true, maintainAspectRatio: false})
    }
}

I use the props to pass the data example.vue

<template>
<line-chart :width="370" :height="246" :chart="chartdata"></line-chart>
</template>
<script>
import LineChart from './vue-chartjs/LineChart'
export default {
components: {
      LineChart
    },
},
data(){
 return{
   chartdata:[]
  }
}
methods:{
  getdata(){
    this.chartdata=[10,20,30,40,50]
    }
}

</script>

when I click the getdata() the chartdata I think it has been passed to the Linechart.js, But why the chart does not update? Still empty


Solution

  • If you want the data to change on the fly, you either need the reactiveMixin http://vue-chartjs.org/#/home?id=reactive-data

    Or you have to trigger an chart update by yourself.

    This is because, even Vue.js is reactive, Chart.js per se is not.

    If you want to update your chart, simply add a watcher to your LineChart.js component and watch for changes in chart. And then call .update()

    import { Line } from 'vue-chartjs'
    
    export default {
      extends: Line,
      props:['chart']
      watch: {
        chart () {
          this.$data._chart.update()
        }
      }
      mounted () {
          this.renderChart({
            labels: ['1','2','3','4','5','6','7'],
            datasets: [
              {
                label: 'Data One',
                backgroundColor: '#F64A32',
                data: this.chart
              }
            ]
          }, {responsive: true, maintainAspectRatio: false})
        }
    }