在Vue中使用Chart.Js

安装Chart.Js

npm install vue-chartjs chart.js --save

引用Chart.Js

import Chart from 'chart.js'

使用Chart.Js

<template>
  <section class='content'>
    <div class='box'>
      <div class='box-body'>
        <div class='row'>
          <div class='col-md-4'>
            <div class="small" v-if="chartDisplay">
              <canvas id="myChart2" ></canvas>
            </div>
          </div>
          <div class='col-md-4'>
            <div class="small" v-if="chartDisplay">
              <canvas id="myChart1" ></canvas>
            </div>
          </div>
    </div>
    <div class="row">
      <div class="col-md-8">
        <canvas id="line-chart"></canvas>
      </div>
    </div>
    <div class="vld-parent">
      <loading :active.sync="isLoading"
               :can-cancel="true"
               :on-cancel="onCancel"
               :is-full-page="fullPage"></loading>
      </div>
      </div>
    </div>
  </section>
</template>
<script>
  /* eslint-disable quotes */
import Loading from 'vue-loading-overlay'
import { Bar } from 'vue-chartjs'
import qs from 'Qs'
import Chart from 'chart.js'
// eslint-disable-next-line no-extend-native
Date.prototype.format = function (fmt) {
    var o = {
      'M+': this.getMonth() + 1,                 // 月份
      'd+': this.getDate(),                    // 日
      'h+': this.getHours(),                   // 小时
      'm+': this.getMinutes(),                 // 分
      's+': this.getSeconds(),                 // 秒
      'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
      'S': this.getMilliseconds()             // 毫秒
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (var k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      }
    }
    return fmt
}
export default {
    extends: Bar,
    components: {
      Loading
    },
    mounted () {
      var ctx2 = document.getElementById('myChart2')
      var ctx1 = document.getElementById('myChart1')
      this.pieChart = new Chart(ctx2, {
        type: 'pie',
        data: {
          labels: ['短信发送成功', '短信发送失败'],
          datasets: [{
            label: '请求占比',
            backgroundColor: ["#3e95cd", "#e8c3b9", "#3cba9f", "#e8c3b9", "#c45850"],
            data: []
          }]
        },
        options: {
          title: {
            display: true,
            text: '短信提醒成功率'
          }
        }
      })
      this.pieChart2 = new Chart(ctx1, {
        type: 'pie',
        data: {
          labels: ['电话提醒成功', '电话提醒失败', '电话提醒未接通'],
          datasets: [{
            label: '请求占比',
            backgroundColor: ["#3e95cd", "#e8c3b9", "#3cba9f", "#e8c3b9", "#c45850"],
            data: []
          }]
        },
        options: {
          title: {
            display: true,
            text: '电话提醒成功率'
          }
        }
      })
      var lineChart = new Chart(document.getElementById("line-chart"), {
        type: 'line',
        data: {
          labels: [1500,1600,1700,1750,1800,1850,1900,1950,1999,2050],
          datasets: [{
            data: [86,114,106,106,107,111,133,221,783,2478],
            label: "短信",
            borderColor: "#3e95cd",
            fill: false
          }, {
            data: [282,350,411,502,635,809,947,1402,3700,5267],
            label: "电话",
            borderColor: "#8e5ea2",
            fill: false
          }, {
            data: [168,170,178,190,203,276,408,547,675,734],
            label: "API",
            borderColor: "#3cba9f",
            fill: false
          }
          ]
        },
        options: {
          title: {
            display: true,
            text: '请求趋势图'
          }
        }
      })
      this.doGetTotalNum()
    },
    data () {
      return {
        fullPage: true,
        isLoading: false,
        pieChart: null,
        pieChart2: null,
        chartDisplay: true
      }
    },
    methods: {
      onCancel () {
        console.log('User cancelled the loader.')
      },
      doGetTotalNum () {
        var thisLocal = this
        var now = new Date() // 一般传入毫秒时间戳进行初始化
        var nowStr = now.format('yyyy-MM-dd hh:mm:ss')
        var object = {
          userId: 'test',
          userName: 'test',
          token: 'abc123',
          startTime: '2020-04-29 00:00:00',
          endTime: '2020-04-29 00:00:00',
          pageSize: 10,
          pageNumber: 0
        }
        object.endTime = nowStr
        this.isLoading = true
        this.$http.post('serviceQuarySummarizing', qs.stringify(object)).then(function (response) {
          if (response.data && response.data.code && response.data.code === 200) {
            console.log(thisLocal.pieChart.data)
            thisLocal.pieChart.data.datasets[0].data.push(response.data.data.SummarizingList.sendMsgSuccess)
            thisLocal.pieChart.data.datasets[0].data.push(response.data.data.SummarizingList.sendMsgFail)
            thisLocal.pieChart2.data.datasets[0].data.push(response.data.data.SummarizingList.callPhoneSuccess)
            thisLocal.pieChart2.data.datasets[0].data.push(response.data.data.SummarizingList.callPhoneFai)
            thisLocal.pieChart2.data.datasets[0].data.push(response.data.data.SummarizingList.callPhoneNoCalling)
            thisLocal.chartDisplay = true
            thisLocal.pieChart.update()
            thisLocal.pieChart2.update()
          } else {
            alert('获取失败')
          }
          thisLocal.isLoading = false
        }).catch(function (error) {
          alert(error)
          thisLocal.isLoading = false
        })
      }
    }
}
</script>

<style lang='css'>
</style>

原文地址:https://www.cnblogs.com/shubin/p/13029988.html