Chartjs-Date selection not happening with a click in chartjs in the context of vuejs

1👍

Firstly, you have to fetch the data and store it inside the data property of Vue. Then, You have to filter the data according to your need.Here is the fiddle.

<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>

Here is the script.

new Vue({
  data: () => ({
    date: [

    ],
    challenge: [],
    data: []
  }),

  mounted() {
    fetch("https://api.wirespec.dev/wirespec/stackoverflow/fetchchartdataforvuejs")
      .then(response => response.json())
      .then(result => {

        this.date = result.date;
        this.challenge = result.challenge;
        this.data = result.date.map((date, index) => ({
          x: new Date(date * 1000),
          y: result.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')

Leave a comment