【发布时间】: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