I'm creating a chart showing data in vuejs, I try to update labels
again but still not working.
In ChartjsComponentLineChart.vue
:
<script>
import { Line } from 'vue-chartjs'
export default {
extends: Line,
props: {
data: {
type: Object,
default: null,
},
options: {
type: Object,
default: null,
},
plugins: {
type: Array,
default: null,
},
styles: {
type: Object,
default: null,
},
},
mounted() {
this.renderChart(this.data, this.options, this.plugins, this.styles)
},
}
</script>
In report.vue
<b-card-body>
<chartjs-component-line-chart
:height="400"
:data="data"
:options="options"
:plugins="plugins"
/>
</b-card-body>
<b-button
variant="primary"
class="btn-tour-finish"
@click="submitData"
>Submit
</b-button>
data() {
return: {
data: {
labels: [],
datasets: [
{
data: [70, 95, 100, 120, 257, 271, 300, 321, 383, 450],
label: "Supper",
borderColor: "#3e95cd",
},
],
},
options: {
title: {
display: true,
text: "Report",
},
responsive: true,
maintainAspectRatio: false,
},
}
},
created() {
this.data.labels = [1980, 1985, 1990, 1995, 2000, 2005, 2010, 2015, 2020, 2025];
},
methods: {
submitData() {
this.data.labels = [1985, 1990, 1995, 2000, 2005, 2010, 2015, 2020, 2025, 2030];
}
}
The chart worked. But when I click submit (submitData())
the labels
doesn't update. Is there a way to update the 'labels' when I click. Give me any ideas. Thanks
CodePudding user response:
Chart.js itself is not reactive, you need to call the update
method yourself when the data is changed. This behaviour of being non reactive out of the box is being taken over by vue-chartjs.
To make it reactive you need to add the reactiveProp
mixin to your lineChart component according to the docs.
import { Line, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins
export default {
extends: Line,
mixins: [reactiveProp],
props: ['options'],
mounted () {
// this.chartData is created in the mixin.
// If you want to pass options please create a local options object
this.renderChart(this.chartData, this.options)
}
}
You can also implement your own watcher and call the update method of chart.js yourself according to the docs
watch: {
data () {
this.$data._chart.update()
}
}