claudios
claudios

Reputation: 6656

Vuechart js not rendering on a component

I'm trying to use the vue-chartjs npm package, but my code below is not rendering the chart. I'm using VueJS 2 and have already installed the package using npm.

<canvas id="chartRecord" width="100%" height="400"></canvas>

<script>
  import { Line } from 'vue-chartjs'
  export default {
    mounted () {
      Line.renderChart({
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        datasets: [{
          label: 'GitHub Commits',
          backgroundColor: '#f87979',
          data: [40, 20, 12, 39, 10, 40, 39, 80, 40, 20, 12, 11]
        }]
      })
    }
  }
</script>

I'm getting this error:

[Vue warn]: Error in mounted hook: "TypeError: __WEBPACK_IMPORTED_MODULE_0_vue_chartjs__.Line.renderChart is not a function"

Upvotes: 1

Views: 4710

Answers (1)

thanksd
thanksd

Reputation: 55634

The vue-chartjs module provides Vue components that are intended to be extended in order to customize.

The correct syntax to do what you're trying to do:

// MyChart.js
import { Line } from 'vue-chartjs'
export default Line.extend({
  mounted() {
    this.renderChart({
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
      datasets: [
        {
          label: 'GitHub Commits',
          backgroundColor: '#f87979',
          data: [40, 20, 12, 39, 10, 40, 39, 80, 40, 20, 12, 11]
        }
      ]
    })
  }
}

Notice that you can simply put this in a .js file as there's no need to specify a template since it's already included in the Line component being imported, and since styling is mostly done in the options of the chart.

You can then import the extended component like any other component:

//Parent.vue
<template>
  <my-chart></my-chart>
</template>

<script>
import MyChart from './MyChart'

export default {
  components: { MyChart }
}
</script>

See the documentation.

Upvotes: 2

Related Questions