如何动态更新chart.js中的数据

n7taea2i  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(308)

如何将数据更新到我在装载时定义的图表中?
我想我没有正确地参考图表?
失败的是data()函数,显示“找不到linechart”,但我如何指定linechart呢?
我已经制作了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>
j5fpnvbx

j5fpnvbx1#

您应该定义变数,将Chart存放在mounted函式之外,以便其他方法可以看见。
所以用这个

let linechart;

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

sandbox

相关问题