在 v-for 中渲染 vuechart

Rendering vuechart inside v-for

我正在联系 API,将结果保存在数据中,然后使用 v-for 在 table 中列出该数据。其中一列包含一个 vuechart,但我似乎无法让它显示任何内容。如果我检查创建的组件,它在 props 数组中有数据,但在获取条上没有骰子。

将 vuechart 图表放在 v-for 循环中有什么特别之处吗?还是我传递的东西不正确?

代码如下:

TrendChart.js

import {Bar} from 'vue-chartjs'

export default {
  extends: Bar,
  name: 'TrendChart',
  props: ['data', 'options'],
  mounted() {
    this.renderChart(this.data, this.options)
  }
}

results.vue

<table>
  <tr v-for="result in results">
  ...
  <td>
    <trend-chart :data="result.trends", :options="{responsive: false, maintainAspectRatio: false}"></trend-chart>
  ...
</table>

如果我在渲染后检查组件,我会看到道具在那里,但数据似乎没有出现在图表上,所以我认为,我还没有看到成功的(这是文本格式的 Vue 开发工具的输出):

props
  chartId:"bar-chart"
  cssClasses:""
  data:Array[12]
  height:400
  options:Object
  maintainAspectRatio:false
  responsive:false
  plugins:Array[0]
  styles:undefined
  width:400

data
  _chart:Unknown Component
  _plugins:Array[0]

检查Vue Chart Guidethis.renderChart()的第一个参数是一个对象而不是一个数组。

例如,从上面的指南中复制:

{
  labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  datasets: [
    {
      label: 'GitHub Commits',
      backgroundColor: '#f87979',
      data: [40, 20, 12, 39, 10, 40, 39, 80, 40, 20, 12, 11]
    }
  ]
}

修复它然后图表应该可以正常工作。

下面是一个简单的演示:

Vue.config.productionTip = false
let RawLineChart = window.VueChartJs.Bar
Vue.component('line-chart', {
  extends: RawLineChart,
  props: ['data', 'options', 'name'],
  mounted () {
    this.renderChart({
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
      datasets: [
        {
          label: this.name,
          backgroundColor: '#f87979',
          data: this.data
        }
      ]
    }, this.options)
  }
})

new Vue({
  el: '#app',
  data() {
    return {
      results: [
        {name:'Chart A', trends: [40, 39, 20, 40, 39, 80, 40]},
        {name:'Chart B', trends: [140, 139, 110, 140, 139, 80, 140]},
        {name:'Chart C', trends: [240, 139, 210, 140, 239, 80, 240]}
      ]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script src="https://unpkg.com/vue-chartjs/dist/vue-chartjs.min.js"></script>
<div id="app">
<table>
  <tr v-for="result in results">
  <td>{{result.name}}</td>
  <td>
    <line-chart :data="result.trends" :name="result.name" :options="{responsive: false, maintainAspectRatio: false}">
    </line-chart>
    </td>
    </tr>
</table>
</div>