如何将具有axios.get()数组数据的渲染条形图导出到vue中的更高级别的组件

时间:2019-05-13 21:32:01

标签: vue.js axios vue-chartjs

我正在父Vue页面上显示一系列图表Vue组件。在使用其中一张图表测试axios调用时,我能够返回一个列表以填充条形图。我一直在跟踪this.bardata直到mount()方法,当我调用this.renderChart(this.bardata,this.options)时,bardata似乎消失了。

当前条形图组件:

<script>
  import axios from 'axios'
  //Importing Bar class from the vue-chartjs wrapper
  import { Bar, mixins } from 'vue-chartjs'
  const API_URL = 'http://localhost:58881'
  //Exporting this so it can be used in other components
  export default {
    extends: Bar,
    mixins: [mixins.reactiveData],
    data () {
      return {
        bardata: {
              labels: ['Failed', 'Successful', 'Total'],
              datasets: [
              {
                label: 'Attempts',
                backgroundColor: '#455A64',
                //Data to be represented on y-axis
                data: null,
                borderWidth: 1
              }
              ]
            },
        //Chart.js options that controls the appearance of the chart
        options: {
          title : {
            display : true,
            position : "top",
            text : "",
            fontSize : 18,
            fontColor : "#111"
          },
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false,
          scales : {
            yAxes : [{
            ticks : {
              min : 0
            }
            }]
          }
        }
      };
    },
    mounted () {
      //renderChart function renders the chart with the datacollection and options object.
      console.log(this.bardata)
      this.renderChart(this.bardata, this.options)
    },
    created() {
        axios.get(API_URL + "/api/admin/GetChart" ,{
          params:{
          chartName: 'LoginsBarChart',
          userToken: this.userToken,
        } ,
        headers: {
          token: this.userToken
        }
        }).then(response => {
            this.bardata.datasets.data = response.data
        })          
      }
  }
</script>

在浏览器的控制台中,this.bardata显示适当的数组[0,2,2]。

这是我的父Vue,它显示图表组件:

<template>
  <section class="container">
    <h1>Usage Analysis Dashboard</h1>
    <div class="Chart">
      <div class="column">
        <h3>Logins vs Failures</h3>
        <logins-bar-chart></logins-bar-chart>
      </div>
    </div>
  </section>
</template>

<script>
  import LoginsBarChart from '@/components/LoginsBarChart.vue'

  export default {
    name: 'VueChartJS',
    components: {
      // Bar Chart 
        LoginsBarChart,
    }
  }
</script>

Console and Frontend Pic (第一次发布,需要10个声誉才能发布实际图像)

总的来说,我看不到哪里出了问题,如果数组一直到在乃至Mounted()方法内部都是正确的,为什么图表没有在浏览器中填充?

在创建axios调用之前,在bardata.datasets.data中,我将对[0,2,2]进行硬编码

 bardata: {
              labels: ['Failed', 'Successful', 'Total'],
              datasets: [
              {
                label: 'Attempts',
                backgroundColor: '#455A64',
                //Data to be represented on y-axis
                data: null,
                borderWidth: 1
              }
              ]
            },

该图表将显示正常。

2 个答案:

答案 0 :(得分:1)

问题是您正在对以Promise结尾的创建方法进行请求。在运行已安装的方法之前,此承诺不会总是解决。我的建议是将renderChart调用移至创建的方法上的.then

class LoginListingBloc extends Bloc<LoginListingEvent, LoginListingStates> {
  final LoginRepository loginRepository;

  LoginListingBloc({this.loginRepository});

  @override
  LoginListingStates get initialState => LoginUninitializedState();

  @override
  Stream<LoginListingStates> mapEventToState(
      LoginListingStates currentState, LoginListingEvent event) async* {
    if (event is LoginEvent) {
      yield LoginFetchingState();
      try {
        final loginInfo = await loginRepository.fetchLoginToPage(
            event.loginInfoModel.username, event.loginInfoModel.password);
        yield LoginFetchedState(userInfo: loginInfo);
      } catch (_) {
        yield LoginErrorState();
      }
    }
  }
}

答案 1 :(得分:0)

我知道了! bardata从未发送回原始的返回参数,所以我想我会尝试使用我的created()设置整个bardata 这是工作结果:

<script>
  import axios from 'axios'
  //Importing Bar class from the vue-chartjs wrapper
  import { Bar, mixins } from 'vue-chartjs'
  const API_URL = 'http://localhost:58881'
  //Exporting this so it can be used in other components
  export default {
    extends: Bar,
    mixins: [mixins.reactiveData],
    data () {
      return {
        bardata: {},
        //Chart.js options that controls the appearance of the chart
        options: {
          title : {
            display : true,
            position : "top",
            text : "",
            fontSize : 18,
            fontColor : "#111"
          },
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false,
          scales : {
            yAxes : [{
            ticks : {
              min : 0
            }
            }]
          }
        }
      };
    },
    created() {
        axios.get(API_URL + "/api/admin/GetChart" ,{
          params:{
          chartName: 'LoginsBarChart',
        } ,
        headers: {
          token: this.userToken
        }
        }).then(response => {
          this.bardata = {
              labels: ['Failed', 'Successful', 'Total'],
              datasets: [
              {
                label: 'Attempts',
                backgroundColor: '#455A64',
                //Data to be represented on y-axis
                data: response.data,
                borderWidth: 1
              }
              ]
            },
            //console.log(this.bardata)
            this.renderChart(this.bardata, this.options)

        })          
      }
  }
</script>