Reputation: 288
I am new to Vuejs, i have implemented chart using Chartjs, i want to add date selector to my chartjs. I have used 4 buttons, so whenever i click any of the button my chart should change accordingly.
Initially i tried implementing each button with each method, but i don't feel that as an effective way to do so.
> Here is my code: https://jsfiddle.net/95kspb70/3/
I want the chart to change when ever i click any of the button that i have used, i mean i have used 4 buttons, suppose say i clicked 3m, my chart should show previous 3months data only.
Please help me with this, I don't know how exactly i should do it in order to solve this.
Upvotes: 1
Views: 912
Reputation: 6058
You need to filter the data based on the date and rerender the chart for the new data.
Here is the working jsfiddle
I add click event @click="selectPeriod"
inside html:
<div id='app'>
<div id="range-selector">
<input type="button" id="1m" @click="selectPeriod" class="period ui-button" value="1m" />
<input type="button" id="3m" @click="selectPeriod" class="period ui-button" value="3m" />
<input type="button" id="6m" @click="selectPeriod" class="period ui-button" value="6m" />
<input type="button" id="all" @click="selectPeriod" class="period ui-button" value="All" />
</div>
<canvas ref='chart' width='800' height='600'></canvas>
</div>
and following js code:
new Vue({
data: () => ({
date: [
1567295500.0,
1567893700.0,
1568615220.0,
1569024000.0,
1569888120.0,
1572456400.0,
1572772560.0,
1574809200.0,
1576706160.0,
1577718000.0,
1578610800.0,
1582650220.0,
1583174000.0,
1584063360.0,
1587427200.0,
1587573420.0,
1588637800.0,
1589587420.0,
1589989800.0
],
challenge: [
0.45,
2.12,
2.55,
3.15,
4.16,
5.56,
6.258,
7.256,
8.364,
9.154,
10.245,
11.654,
12.364,
13.785,
14,
15.32,
16.87,
17.852,
18.254,
19
],
data: []
}),
mounted() {
this.data = this.date.map((date, index) => ({
x: new Date(date * 1000),
y: this.challenge[index]
}))
this.buildGraph(this.data);
},
methods: {
buildGraph(data) {
console.log(data.length);
let ctx = this.$refs.chart.getContext('2d')
let chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
data
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'month',
displayFormats: {
month: 'MMM YYYY'
}
}
}],
yAxes: [{
ticks: {
callback: function(value, index, values) {
return value + 'k';
}
}
}]
}
}
})
},
selectPeriod(event) {
let period = event.target.value;
let minValue = new Date(Math.max(...this.date) * 1000);
let axisXMin = new Date(Math.min(...this.date) * 1000);
switch (period) {
case "1m":
minValue.setMonth(minValue.getMonth() - 1);
break;
case "3m":
minValue.setMonth(minValue.getMonth() - 3);
break;
case "6m":
minValue.setMonth(minValue.getMonth() - 6);
break;
case "1y":
minValue.setYear(minValue.getFullYear() - 1);
break;
default:
minValue = axisXMin;
}
let data = this.data.filter(el => {
return el.x >= minValue
});
this.buildGraph(data);
}
}
}).$mount('#app')
Upvotes: 2