[Chartjs]-VueJs + Chart.js – Avoid ref for reactive updates

4πŸ‘

βœ…

vue-chartjs author here.

About the mixins:
There are two mixins included. Mixins in vue simply extract some logic and functionality into seperate files, so you can reuse them.

Like in the docs said, there are two mixins.

  • reactiveProp and
  • reactiveData

Because, there are two main scenarios, how you pass data to the chart component. Possibility one is for example in a laravel environment where you pass your data over the props directly to your component.

<my-chart :chart-data="..."></my-chart>

The other usecase is, if you have an API and make a fetch / API request.
But then your chart data is not a prop, is a variable in the data() function of vue.

Fix

Well you overcomplicate your code a bit.

You rather need the reactiveProp mixin.

<script>
import { Doughnut, mixins } from 'vue-chartjs'

export default Doughnut.extend({
  mixins: [mixins.reactiveProp],
  props: ["options"],
  
 
  mounted () {
    this.renderChart(this.chartData, this.options)
  }
 
})

</script>

The mixin will create a prop named chartData and add a watcher to it. Every time the data changes, it will either update the chart or re-render. If you add new datasets the chart needs to be re-rendered.

Your Questions

  1. Well you don’t need $ref, if you use the right mixin
  2. camelCase in templates needs to be written with a dash β€˜-β€˜
  3. Maybe it is buggy, because you duplicated the data attribute. The mixins always automatically create your chartData as a property or data() function variable. So you don’t need to create it by your own. However I guess it could be a race condition. Where data is not set in the create() hook of vue. https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram

Leave a comment