简体   繁体   中英

How to dynamically update data in chart.js

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 class="container center">
    <div class="px-3">
      <label for="Product">Select a:</label>
      <select
        class="border-solid border-2 rounded-md p-1 font-bold"
        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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM