ChartJS 带有vue的Charts.js在获取数据后不绘制图表

zxlwwiss  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(165)

这是json响应的样子[[61,57,34],[1,1,3]]我想用第一个数组来存放标签,第二个数组来存放数据。
如果我在app中手动设置labels and data,它仍然有效。
例如labels: ["q", "w", "e"]data: [1, 5, 10]

Vue.component('chart', {
  props: ['labels', 'data', 'type'],
  template: `
    <canvas style="width: 512px; height: 256px"></canvas>
  `,
  mounted: function () {
    new Chart(this.$el, {
      type: this.type,
      data: {
          labels: this.labels,
          datasets: [{
              label: '# of Votes',
              data: this.data,
              borderWidth: 1
          }]
      },
      options: {
          scales: {
              yAxes: [{
                  ticks: {
                      beginAtZero:true
                  }
              }]
          }
        }
      })
  }
});

new Vue({
  el: '#app',
  data: {
    message: "test",
    labels: [],
    data: []
  },
  methods: {
    fetchData: function() {
      this.$http.get('/admin/fetch_data').then(res => {
        this.labels = res.body[0];
        this.data = res.body[1];
      })
    }
  },
  beforeMount() {
    this.fetchData()
  }
});

页面上的组件

<div id="app">
  {{message}}
  <chart :labels="labels" :data="data" type="bar"></chart>
</div>

数据似乎已加载,但页面上没有条形图。

jaxagkaj

jaxagkaj1#

问题是当你正在执行一个异步任务来获取你的数据时,你的数据还没有被获取。到那时,组件的挂载钩子会被空的props调用,因为你作为props传递的数据还没有被加载。
所以这样做:

Vue.component('chart', {
  props: ['labels', 'data', 'type' 'loaded'],
  template: `
    <canvas style="width: 512px; height: 256px"></canvas>
  `,
  watch:{
      loaded(isLoaded){
          if(isLoaded){
              this.drawChart();
          }
      }
  },
  methods:{
      drawChart: function () {
        new Chart(this.$el, {
          type: this.type,
          data: {
              labels: this.labels,
              datasets: [{
                  label: '# of Votes',
                  data: this.data,
                  borderWidth: 1
              }]
          },
          options: {
              scales: {
                  yAxes: [{
                      ticks: {
                          beginAtZero:true
                      }
                  }]
              }
            }
          }) 
    }
  }
});

new Vue({
  el: '#app',
  data: {
    message: "test",
    labels: [],
    data: [],
    loaded: false
  },
  methods: {
    fetchData: function() {
      this.$http.get('/admin/fetch_data').then(res => {
        this.labels = res.body[0];
        this.data = res.body[1];
        this.loaded = true;
      })
    }
  },
  created() {
    this.fetchData()
  }
});

html格式

<div id="app">
  {{message}}
  <chart :labels="labels" :data="data" :loaded="loaded" type="bar"></chart>
</div>
  • 在root vue示例中添加一个设置为false属性loaded,并将其作为prop传递
  • 在由ths.$http.get()请求返回的promise的成功回调中,将loaded更改为true
  • 在您的chart组件中设置一个监视器来监视这个loaded属性
  • loaded属性changes to为真时调用drawChart方法'

相关问题