Home > Net >  How to dynamically update data in chart.js
How to dynamically update data in chart.js

Time:07-08

How to update the data to the chart that I define when I mount?

I think that I fail to properly reference the chart?

It is the data() function that fails, with "Could not find linechart", but how do I specify linechart?

I have made this code sandbox

<template>
  <div >
    <div >
      <label for="Product">Select a:</label>
      <select
        
        v-on:input="outputData()"
        id="Product"
        aria-placeholder="Product"
      >
        <option value="" disabled selected>Product</option>
        <option>1</option>
      </select>
    </div>
    <div>
      <canvas id="line-chart"></canvas>
    </div>
  </div>
</template>

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

export default {
  name: "line-plot",
  mounted() {
    const ctx = document.getElementById("line-chart");
    const linechart = new Chart(ctx, this.chartData);

    return linechart;
  },
  data() {
    return {
      chartData: {
        type: "line",
        data: {
          labels: ["a", "b", "c"],
          datasets: [
            {
              label: "Contract",
              data: [5, 5, 5],
              borderColor: "#9B202A",
              borderWidth: 3,
            },
            {
              label: "FWD",
              data: [5, 10, 15],
              borderColor: "#6F6F6F",
              borderWidth: 3,
            },
          ],
        },
      },
      options: [],
    };
  },
  methods: {
    outputData() {
      const contractPrice = {
        label: "Contract",
        data: [6, 6, 6],
        borderColor: "#9B202A",
        borderWidth: 3,
      };
      const fwdPrice = {
        label: "FWD",
        data: [10, 10, 10],
        borderColor: "#6F6F6F",
        borderWidth: 3,
      };

      const labels = ["a", "b", "c"];

      this.chartData.data.labels = labels;
      this.chartData.data.datasets[0] = contractPrice;
      this.chartData.data.datasets[1] = fwdPrice;

      linechart.update();
    },
  },
};
</script>

<style>
.center {
  margin: auto;
}
</style>

CodePudding user response:

You should define your variable to hold the Chart outside the mounted function in order to be visible to the other methods.

So instead use this

let linechart;

export default {
  name: "line-plot",
  mounted() {
    const ctx = document.getElementById("line-chart");
    linechart = new Chart(ctx, this.chartData);
  },

sandbox

  • Related