I have a linear line chart and a button to toggle the visibility of the trendline.
Showing the trendline works fine, but when I click the button again to hide the trendline, nothing happens.
I have no idea why, perhaps it's a bug in vue-chartjs
v4.2.1 or maybe I'm doing something wrong with my code. I even try to manually update the chart via ref, but no luck.
<template>
<div>
<line-chart
ref="chart"
:chartData="chartData"
:chartOptions="chartOptions"
/>
<button @click="toggleTrendline">
{{ showTrendline ? "Hide" : "Show" }} trendline
</button>
</div>
</template>
<script>
import { Line } from "vue-chartjs/legacy";
export default {
components: { "line-chart": Line },
data() {
return {
showTrendline: false,
};
},
computed: {
chartOptions() {
return {
responsive: true,
maintainAspectRatio: false,
};
},
chartData() {
let data = {
labels: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
],
datasets: [
{
label: "Data One",
backgroundColor: "#f87979",
data: [40, 20, 12, 39, 10, 40, 39, 80, 40, 20, 12, 11],
},
],
};
if (this.showTrendline)
data.datasets[0].trendlineLinear = {
colorMin: "#2d9cdb",
colorMax: "#2d9cdb",
lineStyle: "solid",
width: 2,
};
else delete data.datasets[0].trendlineLinear;
return data;
},
},
methods: {
toggleTrendline() {
this.showTrendline = !this.showTrendline;
if (!this.showTrendline) {
this.$refs.chart.getCurrentChart().update("none");
}
},
},
};
</script>
Here is a reproducible sandbox: https://codesandbox.io/s/vue-chartjs-demo-forked-kujr7m?file=/src/components/LineChart.vue:0-1463
Here is a working version with vanilla js: https://codesandbox.io/s/working-trendline-q31h0o?file=/src/index.js It works fine with vanilla js, so I believe either my vue code is wrong or vue-chartjs has a bug.
...
else
data.datasets[0].trendlineLinear = null;