Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update Chartjs Chart datasets inside a Vuejs

Really appreciate your support
I want to update a Chartjs datasets when a button is clicked

here is my code below

<template>
  <v-card>
    <v-layout>
      <v-main style="height: 250px">
        <v-btn @click="DataSetOne">Add Chart</v-btn
        ><v-btn @click="DataSetTwo">Change Data</v-btn>
        <canvas id="myChart6" style="height: 400px"> </canvas>
      </v-main>
    </v-layout>
  </v-card>
</template>

<script>
import Chart from "chart.js/auto";

export default {
  name: "HomeView",
  components: {},
  data: () => ({}),
  watch: {},
  computed: {},
  methods: {
    DataSetTwo() {
      let myChart6 = document.getElementById("myChart6"), config;
      myChart6.data.datasets[0].data = [58, 12, 6, 9, 12, 3, 9, 2];
      myChart6.update();
    },
    DataSetOne() {
      let labels = [1, 2, 3, 4, 5, 6, 7, 9];
      let data = {
        labels: labels,
        datasets: [
          {
            type: "line",
            label: "Graph",
            backgroundColor: "rgb(171, 235, 198)",
            borderColor: "rgb(171, 235, 198)",
            data: [8, 12, 6, 9, 12, 3, 9, 2],
            hidden: false,
          },
        ],
      };
      let config = {
        data: data,
        options: {
          scales: {
            y: {
              beginAtZero: true,
            },
          },
        },
      };
      let myChart6 = new Chart(document.getElementById("myChart6"), config);
      myChart6;
    },
  },
  mounted() {},
};
</script>


it give me error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I Tried Chart.update(), chart.destroy() but it doesn’t work, I can make it work in plain JS but not in Vuejs ,need your support making the datasets of Chartjs update in Vuejs

>Solution :

You are getting the dom element. This won’t work. You need to get the chart instance. So instead of

let myChart6 = document.getElementById("myChart6");

You need to use:

let myChart6 = Chart.getChart("myChart6");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading