TimeSocks
344
2
Vue

Multiple charts with Vue and charts.js

Posted 4 months ago by TimeSocks

Hi folks,

I'm going through the 'Charts and You' series. It's a little out of date both in terms of Vue and Charts.js, but I think I've made the necessary changes, namely, using mounted instead of ready, and updating the syntax for instantiating a new Chart.

However, I have hit a snag with adding multiple charts to the page. In the video, Jeff removes the tag's ID, and changes the context to:

var context = this.$el.getContext('2d');

However, this gives me an error:

this.$el.getContext is not a function

Here's my Vue component:

<template>
  <section>
    <canvas width="600" height="400"></canvas>
  </section>
</template>

<script>
    export default {
        mounted() {
            console.log('Graph component mounted.')
            var context = this.$el.getContext('2d');
            var data = {
                            labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
                            datasets: [{
                                label: 'My First dataset',
                                data: [
                                    30,120,122
                                ],
                                fill: false,
                            }, {
                                label: 'My Second dataset',
                                fill: false,
                                data: [
                                    45,35,23
                                ],
                            }],
                    options: {
                      responsive:true,
                    }
                }
            new Chart(context, { type: "line", data: data });
        }
    }
</script>

Here's the Vue part of app.js

const app = new Vue({
    el: '#graphs'
});

And here's the page markup:

<section id="graphs">
    <div class="container">
      <div class="columns">
        <div class="column">
          <h2>Temperature</h2>
          <graph></graph>
        </div>
        <div class="column">
          <h2>Humidity</h2>
          <graph></graph>
        </div>
        <div class="column">
          <h2>Pressure</h2>
          <graph></graph>
        </div>
      </div>
    </div>
  </section>

Any ideas?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.