I want my function to update the data displayed by a vue chart js each time I click on a button but I get this error: "_vm.chartData is not a function".
I use computed properties as told in the guide but I'm doing something wrong and I don't know what.
here is my code :
<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>
Any help would be appreciated
CodePudding user response:
In Vue, the template is already bound to the context, so you don't need this
for variables and methods.
Try this (no pun intended):
*Note the new variable 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>