如何在一个组件Vue上创建多个图表

时间:2019-06-17 05:37:38

标签: javascript vue.js chart.js

我想在一个.vue component和一个.js文件中从chart.js创建多个图表,我该如何创建它?

到目前为止,我尝试为每个图表创建另一个.js文件。

这里是我的代码

LineChart.js文件

import {Line} from 'vue-chartjs'

export default {
  extends: Line,
  mounted () {

    this.renderChart({
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
      datasets: [
        {
          label: 'Data One',
          backgroundColor: '#FC2525',
          data: [40, 39, 10, 40, 39, 80, 40]
        },{
          label: 'Data Two',
          backgroundColor: '#05CBE1',
          data: [60, 55, 32, 10, 2, 12, 53]
        }
      ]
    }, {responsive: true, maintainAspectRatio: false})

  }
}

Step2.vue组件

<template>
  <div class="Chart">
    <h2>Linechart</h2>
    <line-example></line-example>
  </div>
</template>

<script>
import LineExample from './LineChart.js'
export default {
  name: 'tes',
  components: {
    LineExample
  }
}
</script>

此代码用于一张图表,如果我想添加更多图表,则必须创建另一个.js文件。

1 个答案:

答案 0 :(得分:1)

您可以使用props

注意-有关反应性问题,您可以查看https://vue-chartjs.org/guide/#updating-charts

JS

import { Line, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins


export default {
  extends: Line,
  mixins: [reactiveProp],
  props: {
    labels: Array,
    datasets: Object
  },
  mounted () {
    this.renderChart({
      labels: this.labels,
      datasets: this.datasets,
    }, {responsive: true, maintainAspectRatio: false})
  }
}

组件

        <template>
  <div class="Chart">
    <h2>Linechart 1</h2>
    <line-example :labels="labels" :datasets="datasets"></line-example>
    <h2>Linechart 2</h2>
    <line-example :labels="labels2" :datasets="datasets2"></line-example>
  </div>
</template>

<script>
import LineExample from './LineChart.js'
export default {
  name: 'tes',
  components: {
    LineExample
  },
  data () {
    return {
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
      labels2: ['Foo', 'Bar'],
      datasets: [
        {
          label: 'Data One',
          backgroundColor: '#FC2525',
          data: [40, 39, 10, 40, 39, 80, 40]
        },{
          label: 'Data Two',
          backgroundColor: '#05CBE1',
          data: [60, 55, 32, 10, 2, 12, 53]
        }
      ],
      datasets2: [
        {
          label: 'Data One',
          backgroundColor: '#FC2525',
          data: [1, 2]
        },{
          label: 'Data Two',
          backgroundColor: '#05CBE1',
          data: [3, 4]
        }
      ]
    }
  }
}
</script>