使用Chart.js动态呈现图表

时间:2018-11-23 13:27:32

标签: vue.js vuejs2 chart.js

因此,我对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)时,会进行更新,但是我无法使其顺利运行。 documentation说要使用

之类的函数
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,
    };
},

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

2 个答案:

答案 0 :(得分:0)

由于reactiveProp mixin应该负责更新as described in the docs,因此尚不清楚您想做什么以及用例为何不起作用。

但是,您也许应该实现自己的观察程序,在其中可以运行更新代码。像这样:

watch: {
  chartData() {
    this.$data._chart.update();
  }
}

基本上,您可以访问chartthis.$data._chart的所有方法。

或者随时在其他更适合您的工作流程的地方添加this.$data._chart.update()呼叫。

另外,请注意有一个拼写错误:charOptions而不是chartOptions

答案 1 :(得分:0)

这就是我的解决方案:

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进行动态统计渲染的唯一方法。

相关问题