Search code examples
vue.jschart.jsvue-chartjs

Vue-chartjs not rendering chart until page resize


I am using vue-chartjs to create charts for my application. I am passing the chartData as a prop. My chart doesn't render at first but does when I resize the window. Here is my code. First the chart component:

<script>
    import { Doughnut, mixins } from "vue-chartjs";
    const { reactiveProp } = mixins;
    export default {
        extends: Doughnut,
        mixins: [reactiveProp],
        mounted() {
            this.render();
        },
        methods: {
            render() {
                console.log(this.chartData)
                let options = {
                    responsive: true,
                    maintainAspectRatio: false,
                    legend: {
                        display: false,
                    },
                };
                this.renderChart(this.chartData, options);
            },
        },
    };
</script>

Now here is the code from the component where the chart is displayed:

template part

<v-container>
    <ProjectDoughnutChart :chart-data="chartData" />
</v-container>

script part

components: {
    ProjectDoughnutChart,
},

data() {
    return {
        chartData: {
            labels: [],
            datasets: [
                {
                    backgroundColor: [],
                    hoverBackgroundColor: [],
                    data: [],
                },
            ],
        },
    };
},

setChartsTimesheets() {
    this.timesheets.forEach((timesheet) => {
        let typeTotal = 0;
        this.timesheets
            .filter((timesheet1) => timesheet1.type==timesheet.type)
            .forEach((timesheet1) => {
                typeTotal+=timesheet1.billableAmount;
            });
        if (this.chartData.labels.indexOf(timesheet.type) === -1) {
            let colors = this.getTaskColors(timesheet.type);
            this.chartData.labels.push(timesheet.type);
            this.chartData.datasets[0].data.push(typeTotal);
            this.chartData.datasets[0].backgroundColor.push(colors.color);
            this.chartData.datasets[0].hoverBackgroundColor.push(colors.hover);
        }
    });
},

Solution

  • Solved the problem using a similar solution as "Chart with API data" from the documentation.

    TL;DR: Adding a v-if on the chart