【问题标题】:Cannot read properties of null function();无法读取空函数()的属性;
【发布时间】:2022-10-07 19:58:25
【问题描述】:

我希望我的函数在每次单击按钮时更新 vue 图表 js 显示的数据,但出现此错误:“无法读取 null chartData 的属性”。

我按照指南中的说明使用计算属性,但我做错了,我不知道为什么。

这是我的代码:

<template>
  <div>
  <Bar
    :chart-options="chartOptions"
    :chart-data="chartData"

  />
  <button v-on:click="this.chartData()">
    Change Data
</button>
  </div>
  
  
</template>

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

import {
  Chart as ChartJS,
  Title,
  Tooltip,
  Legend,
  BarElement,
  CategoryScale,
  LinearScale
} 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',
              'March',
              'April',
              'May',
              'June',
              'July',
              'August',
              'September',
              'October',
              'November',
              'December'
            ],
            datasets: [
              {
                label: 'Data One',
                backgroundColor: '#f87979',
                data: [
                  this.getRandomInt(),
                  this.getRandomInt(),
                  this.getRandomInt(),
                  this.getRandomInt(),
                  this.getRandomInt(),
                  this.getRandomInt(),
                  this.getRandomInt(),
                  this.getRandomInt(),
                  this.getRandomInt(),
                  this.getRandomInt(),
                  this.getRandomInt(),
                  this.getRandomInt()
                ]
              }
              ]
          };
        console.log(updatedChartData.datasets)
        return updatedChartData;
      },
  },
  methods:{
    
    getRandomInt() {
        return Math.floor(Math.random() * (50 - 5 + 1)) + 5
      }
  }
  
  
}
</script>

任何帮助,将不胜感激

【问题讨论】:

    标签: javascript vue.js chart.js computed-properties vue-chartjs


    【解决方案1】:

    在vue中,模板已经绑定到上下文了,所以变量和方法不需要this

    试试这个(没有双关语):

    <button v-on:click="chartData">
        Change Data
    </button>
    

    【讨论】:

      猜你喜欢
      • 2018-06-15
      • 2021-09-30
      • 2022-10-13
      • 2017-01-16
      • 1970-01-01
      • 2022-01-12
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多