1

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"

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Can you please explain a lil bit? and where should I put that script? and how to access it inside my component. Thank!
Updated my answer
Tried it and added Chartrecord.js inside js folder. my components are inside components folder but no luck.
What do you mean "no luck"? Are you getting an error?
Yes it says Cannot find module Unexpected token, expected , (17:0)`
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.