在vuejs上下文中单击chartjs不会发生日期选择 [英] Date selection not happening with a click in chartjs in the context of vuejs

查看:46
本文介绍了在vuejs上下文中单击chartjs不会发生日期选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用chartjs来显示图表,并且我正在使用API​​来获取我的数据,并且同样将其馈送到图表中.

I have used chartjs in order to display chart, and I am using API to fetch my data and same is fed to the chart.

这是我的Chart_from_API.vue

Here is my Chart_from_API.vue

<template>
  <div class="chart-container" style="position: relative; height: 25vh; width:100%;">
<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 id="DisplayChart" ></canvas>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  name: 'Chart_from_API',
  data () {
    return {
      Chart_data: []
    }
  },
   mounted () {
       this.display(this.Chart_data)
   },
   methods: {
       display (Chart_data) { `this.$http.get('https://api.wirespec.dev/wirespec/stackoverflow/fetchchartdataforvuejs') //Your API has to be given here`
      .then((response) => {
        const result = response.data
        const ctx = document.getElementById('DisplayChart').getContext('2d')
        for (let i = 0; i < result.date.length; i++) {
          Chart_data.push({
            x_axis: moment(result.date[i], 'X').toDate(),  //To Convert Unix Timestamp into Date
            y_axis: result.challenge[i]
          })
        }
        // eslint-disable-next-line init-declarations,prefer-const
        let myChart
        if (myChart !== undefined) {
          myChart.destroy()
        }

        // eslint-disable-next-line no-undef
        myChart = new Chart(ctx, {
          type: 'line',
          data: {
            datasets: [
              {
                label: 'Chart_from_API',
                data: this.Chart_data,
                borderColor: '#EA5455',
                lineTension: 0
              }
            ]
          },
          options: {
            lineTension: 0,
            maintainAspectRatio: false,
            legend: {
              display: false
            },
            scales: {
              yAxes: [
                {
                  scaleLabel: {
                    display: false
                  },
                  ticks: {
                    beginAtZero: true,
                    // eslint-disable-next-line no-unused-vars
                    callback (value) {
                      return `${value  }k`    // y-axis value will append k to it
                    }
                  }
                }
              ],
              xAxes: [
                {
                  type: 'time',
                  time: {
                    unit: 'month'
                  },
                  scaleLabel: {
                    display: true,
                    labelString: ''
                  }
                }
              ]
            }
          }
        })
      })
      .catch((error) => {
        console.log(error)
      })
  },
 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.Chart_data.filter(el => {
        return el.x >= minValue
      })
      this.display(data);
    }
 }

}

如果我单击日期选择"按钮中的任何一个,这就是我得到的错误:

Here are the errors that i am getting if i click any of the button for Date selection:

请告诉我代码中是否有任何错误,我想知道为什么会收到这些错误.

Please tell if there are any mistakes in my code, and i want to know why i am getting those errors.

推荐答案

首先,您必须获取数据并将其存储在Vue的data属性中.然后,您必须根据需要过滤数据.这是小提琴.

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>

这是脚本.

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

这篇关于在vuejs上下文中单击chartjs不会发生日期选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆