首页 > 解决方案 > 用chartjs动态渲染图表

问题描述

所以我对 Vue.js 很陌生,我想在页面上显示一个动态呈现的图表。到目前为止我有

/*/barChart.js
import { Bar, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins

export default {
    extends: Bar,
    mixins: [reactiveProp],
    props: ['options'],
    mounted () {
        this.renderChart(this.chartData, this.options)
    },
}

在我的主 Vue 文件中

/*/stats.js
const stats = new Vue({
    el: '#app',
    components:{
        "bar-chart": barChart,
    },
    data: function () {
        return {
            chartData: {},
            charOptions: {},
        }
    },
    watch:{
        campaignIds: function(){
            this.fillInStats();
        }
    },
    methods: {
        fillInStats: function(){

        //here I'd like to push data in the chart or remove them depending on a list of Id's.
        }
    },
    //etc
}

因此,当我“手动”更新数据(通过直接设置this.chartData)时,会有一个更新,但我无法让它顺利工作。文档说要使用类似的功能

function addData(chart, label, data) {
    chart.data.labels.push(label);
    chart.data.datasets.forEach((dataset) => {
        dataset.data.push(data);
    });
    chart.update();
}

而且我上班没有问题,this.chartData.labels.push(label)但我不确定如何正确调用chart.update()我的情况(我仍然不熟悉视图的结构)。

这是 HTML:

<div class="card-body">
    <bar-chart :chart-data="chartData" :options="chartOptions" :height="100"></bar-chart>
</div>

编辑

我通过添加使其工作

data: function () {
    return {

        chartData:{labels: ['Destinataires', 'Non-envoyés', 'Non-lus', 'Lus'], datasets: [{label: '', backgroundColor: 'white', data: [0, 0, 0, 0]}]},
        chartOptions: {scales: {yAxes: [{ticks: {beginAtZero:true}}]}},
        dataSets: [],
        //etc
    }
},

并像这样更新数据:

addInStats: function(id){

    let color = this.pickColor();

    let dataSet = {
        label: this.campaignsList[id].name,
        backgroundColor: color,
        data: [this.subscriberCountArray[id], this.nonSentCountArray[id], this.nonReadCountArray[id], this.readCountArray[id]]
    };

    this.dataSets.push(dataSet);

    this.chartData = {
        labels: ['Destinataires', 'Non-envoyés', 'Non-lus', 'Lus'],
        datasets: this.dataSets,
    };
},

但是现在,一旦我添加了几次数据,整个图表就会变成空白

标签: vue.jsvuejs2chart.js

解决方案


所以这是我的解决方案:

import barChart from 'path/to/barChart'

const stats = new Vue({
    //
components:{
    "bar-chart": barChart,
},
data: function () {
    return {
        barChartOptions: {responsive: true, scales: {yAxes: [{ticks: {beginAtZero:true}}]}},
        barChartData: [],
        subscriberCountArray: null,
        readCountArray: null,
        colorArray: [],
    //
    }
},
methods: {
    initStats: function() {
        axios.post(
            //get the data and 

        ).then(response => {
            if(response.data.success) {

                this.campaignsList = response.data.campaignsList;

                this.subscriberCountArray = response.data.subscriberCountArray;
                this.readCountArray = response.data.readCountArray;

                let barDataSets = [];

                for(let i = 0; i < this.campaignIds.length; i++){

                    let currentId = parseInt(this.campaignIds[i]);

                    let color = '';
                    let rgba = [];

                    if(this.colorArray[currentId]){
                        color = this.colorArray[currentId];
                    }else{
                        //pickcolor
                    }

                    barDataSets.push({
                        label: this.campaignsList[currentId].name,
                        backgroundColor: color,
                        data: [this.subscriberCountArray[this.campaignsList[currentId].id], this.readCountArray[this.campaignsList[currentId].id]]
                    });

                this.barChartData = {labels: ['Destinataires', 'Lus'], datasets: barDataSets};

    },
    checkCampaign: function(id){
        if(this.campaignIds.length === 0 || !this.campaignIds.includes(id)){
            this.campaignIds.push(id);
        }else{
            this.campaignIds.splice(this.campaignIds.indexOf(id), 1);
        }
        this.initStats();
    },
    pickColor: function(interval = null, type = null, base = null){
        //
    },
},
mounted(){
    this.initStats();
}

在模板中:

<bar-chart :chart-data="barChartData" :options="barChartOptions"></bar-chart>

并在barChart.js

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

export default {
    extends: Bar,
    mixins: [reactiveProp],
    props: ['options'],
    mounted () {
        this.renderBarChart();
    },
    methods: {
        renderBarChart: function(){
            this.renderChart(this.chartData, this.options);
        }
    },
    watch: {
        chartData: function () {
            this.renderBarChart();
        }
    }
}

似乎不是一种非常有效的方法,但这是我可以使用 vue 进行动态统计渲染的唯一方法。


推荐阅读