ChartJS 图表JS未在Laravel Livewire中重新呈现

b5buobof  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(203)

每当数据发生变化时,ChartJS就不会重新呈现图表。
这是流程。
每当我按下按钮时,它都会触发事件并刷新整个图表组件。我可以看到数据正在更新({{$countPublished}}),但图表没有更新
有人能帮忙吗?谢谢

<canvas id="pieChart"></canvas>
        <div class="flex justify-center mt-4 space-x-3 text-sm text-gray-600 dark:text-gray-400">
            <!-- Chart legend -->
            <div class="flex items-center">
                <span class="inline-block w-3 h-3 mr-1 bg-red-200 rounded-full"></span>
                <span>Pending</span>
            </div>
            <div class="flex items-center">
                <span class="inline-block w-3 h-3 mr-1 bg-purple-700 rounded-full"></span>
                <span>Published {{$countPublished}} </span>
            </div>
        </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"> </script>
<script>
    /**Doughnut Chart */
    var ctx = document.getElementById('pieChart').getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            datasets: [{
                data: [{{$countPublished}}, {{$countunPublished}}],
                backgroundColor: ['#7e22ce', '#fecaca'],
                label: 'Post',
            }, ],
            labels: ['Published', 'Reviewing'],
        },
        options: {
            responsive: true,
            cutoutPercentage: 60,
            legend: {
                display: false,
            },
        },
    });

    function updateConfigByMutating(Chart) {
        myChart.data.datasets.data = [{{$countPublished}}, {{$countunPublished}}],
        myChart.update();
            }
xggvc2p6

xggvc2p61#

找到了解决办法。
必须在按下按钮时触发emit事件,同时触发$data下包含的值。
然后在我的刀片文件中添加了这个

window.onload = function() {
Livewire.on('refreshCharts', ($data) => {
    var ctx = document.getElementById('pieChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
        datasets: [{
            data:  $data,
            backgroundColor: ['#7e22ce', '#fecaca'],
            label: 'Post',
        }, ],
        labels: ['Published', 'Reviewing'],
    },
    options: {
        responsive: true,
        cutoutPercentage: 50,
        legend: {
            display: false,
        },
    },
    });  
})

}

相关问题