ChartJS function()不是函数;

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

我希望我的函数在每次单击按钮时更新vue图表js显示的数据,但我得到了以下错误:“_vm.chartData不是函数”。
我按照指南中的说明使用了计算属性,但我做错了什么,我不知道是什么。
下面是我代码:

<template>
  <div>
  <Bar
    :chart-options="chartOptions"
    :chart-data="chartData"
  />
  <button v-on:click="chartData()">
    Change Data
</button>
  </div>

</template>

<script>
import { Bar } from 'vue-chartjs/legacy'

import {
  Chart as ChartJS,
  Title,
} from 'chart.js'

ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)

export default {
  name: 'BarChart',
  components: {
    Bar
  },
  data() {
    return {
      chartOptions: {
        responsive: true,
        maintainAspectRatio: false
      }
    }
  },
computed :{
  chartData() { 
        const updatedChartData = {
            labels: [
              'January',
              'February',

            ],
            datasets: [
              {
                data: [
                  this.getRandomInt(),
                  this.getRandomInt(),
                ]
              }
              ]
          };
        console.log(updatedChartData.datasets)
        return updatedChartData;
      },
  },
  methods:{

    getRandomInt() {
        return Math.floor(Math.random() * (50 - 5 + 1)) + 5
      }
  }

}
</script>

任何帮助都将不胜感激

myss37ts

myss37ts1#

在Vue中,模板已经绑定到上下文,所以变量和方法不需要this
试试这个(没有双关语):* 请注意新变量chartDataValues

<template>
  <div>
    <Bar
      :chart-options="chartOptions"
      :chart-data="chartDataValues"
    />
    <button v-on:click="chartData">
      Change Data
    </button>
  </div>
</template>

<script>
import { Bar } from 'vue-chartjs/legacy'

import {
  Chart as ChartJS,
  Title,
} from 'chart.js'

ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)

export default {
  name: 'BarChart',
  components: {
    Bar
  },
  data() {
    return {
      chartOptions: {
        responsive: true,
        maintainAspectRatio: false
      },
      chartDataValues: {}
    }
  },
  methods: {
    chartData() { 
      const updatedChartData = {
        labels: [ 'January', 'February' ],
        datasets: [{
          data: [ this.getRandomInt(), this.getRandomInt(), ]
        }]
      };
      console.log(updatedChartData.datasets)
      this.chartDataValues = updatedChartData;
    },

    getRandomInt() {
      return Math.floor(Math.random() * (50 - 5 + 1)) + 5
    }
  }

}
</script>

相关问题