在vue中使用chart.js

安装和引入chart.js

npm install chart.js --save
import Chart from 'chart.js'

html

<template>
  <canvas id="chart"></canvas>
</template>

methods添加创建图表

methods: {
  createChart(chartId, chartData) {
    const ctx = document.getElementById(chartId);
    const { type, data, options } = chartData;
    const myChart = new Chart(ctx, {
      type: type,
      data: data,
      options: options,
    });
  }
}

图表数据

const chartData = {
  type: 'line',
  data: {
    labels: [...],
    datasets: [
      {
        label: '...',
        data: [0, 0, 1, 2, 67, 62, 27, 14],
        backgroundColor: [...],
        borderColor: [...],
        borderWidth: 2
      },
      {
        label: '...',
        data: [4.8, 12.1, 12.7, 6.7, 139.8, 116.4, 50.7, 49.2],
        backgroundColor: [...],
        borderColor: [...],
        borderWidth: 2
      }
    ]
  },
  options: {
    // ...
  }
};

图表初始化

export default {
  data () {
    return { chartData }
  },
  mounted () {
    this.createChart('chart', this.chartData)
  },
  methods: {
    createChart () { // ... }
  }
}

参考:
Chart.js | Open source HTML5 Charts for your website
Using Chart.js with Vue.js ← Alligator.io

Comments
Write a Comment