Vue-chartjs 在调整页面大小之前不呈现图表

Vue-chartjs not rendering chart until page resize

我正在使用 vue-chartjs 为我的应用程序创建图表。我将 chartData 作为道具传递。我的图表一开始不呈现,但在我调整 window 大小时呈现。这是我的代码。首先是图表组件:

<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>

下面是显示图表的组件的代码:

模板部分

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

脚本部分

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);
        }
    });
},

使用与文档中的“Chart with API data”类似的解决方案解决了问题。

TL;DR:在图表上添加 v-if

对于有类似问题但不使用 vue.js 或 官方 解决方案的人来说,解决不了问题。我必须 chart.update() 图表来显示值,这些值是在创建图表后添加的。

参见示例。如果您注释 chart.update() 行,则在 window 调整大小之前图表不会刷新。

let chart = new Chart(document.getElementById("chart"), {
  type: "line",
  data: {
    labels: ["a", "b", "c", "d", "e", "f"],
    datasets: [{
      label: 'Dataset 1',
      data: [1, 5, 12, 8, 2, 3],
      borderColor: 'green',
    }]
  },
  options: {
    interaction: {
      mode: 'index',
      intersect: true,
    },
    stacked: false,
    responsive: true,
  }
});

// adding data to graph after it was created (like data from API or so...)
chart.data.labels.push("new data");
chart.data.datasets[0].data.push(9);

// with chart.update(), the changes are shown right away
// without chart.update(), you need to resize window first 
chart.update();
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="chart"></canvas>