Update Chartjs Chart datasets inside a Vuejs

Advertisements

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

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");

Leave a ReplyCancel reply