Chart.js in Vue + Laravel API Error : Failed to mount compenent + failed to create chart


I am trying to implement chart.js in my Vue3 Project, I have looked at wrappers but they don’t seem to work for me (unless you know any tat do?). Then I found a tutorial on how to do it with plain javascript. I tried it and I’ve almost got it to work, but I can’t fix the last few issues.

In my project I am using Vuetify, Vuex, and Vue Router.

I have a "Graphs" component, where I want to render all my different graphs.

<template>
  <div>
    <PlanetChart/>
  </div>
</template>

<script>
import PlanetChart from '@/components/Graphs/Graph.vue'

export default {
  name: 'App',
  components: {
    PlanetChart
  }
}
</script>

I have my Graph.vue, this is where I render a single chart.

<script>
import Chart from 'chart.js/auto'
import planetChartData from '../../planet-data.js'

export default {
  name: 'PlanetChart',
  data() {
    return {
      planetChartData: planetChartData
    }
  },
  mounted() {
    const ctx = document.getElementById('planet-chart');
    new Chart(ctx, this.planetChartData);
  }
}
</script>

Lastly, I have a javascript that contains the chart. planet-data.js :

export const planetChartData = {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
  };
  
  export default planetChartData;

Source: Vue – Stack Overflow

November 26, 2021
Category : News
Tags: chart.js | javascript | vue router | Vue.js | vuex

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.