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

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

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

  1. <canvas id="pieChart"></canvas>
  2. <div class="flex justify-center mt-4 space-x-3 text-sm text-gray-600 dark:text-gray-400">
  3. <!-- Chart legend -->
  4. <div class="flex items-center">
  5. <span class="inline-block w-3 h-3 mr-1 bg-red-200 rounded-full"></span>
  6. <span>Pending</span>
  7. </div>
  8. <div class="flex items-center">
  9. <span class="inline-block w-3 h-3 mr-1 bg-purple-700 rounded-full"></span>
  10. <span>Published {{$countPublished}} </span>
  11. </div>
  12. </div>
  13. <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"> </script>
  14. <script>
  15. /**Doughnut Chart */
  16. var ctx = document.getElementById('pieChart').getContext('2d');
  17. var myChart = new Chart(ctx, {
  18. type: 'doughnut',
  19. data: {
  20. datasets: [{
  21. data: [{{$countPublished}}, {{$countunPublished}}],
  22. backgroundColor: ['#7e22ce', '#fecaca'],
  23. label: 'Post',
  24. }, ],
  25. labels: ['Published', 'Reviewing'],
  26. },
  27. options: {
  28. responsive: true,
  29. cutoutPercentage: 60,
  30. legend: {
  31. display: false,
  32. },
  33. },
  34. });
  35. function updateConfigByMutating(Chart) {
  36. myChart.data.datasets.data = [{{$countPublished}}, {{$countunPublished}}],
  37. myChart.update();
  38. }
xggvc2p6

xggvc2p61#

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

  1. window.onload = function() {
  2. Livewire.on('refreshCharts', ($data) => {
  3. var ctx = document.getElementById('pieChart').getContext('2d');
  4. var myChart = new Chart(ctx, {
  5. type: 'doughnut',
  6. data: {
  7. datasets: [{
  8. data: $data,
  9. backgroundColor: ['#7e22ce', '#fecaca'],
  10. label: 'Post',
  11. }, ],
  12. labels: ['Published', 'Reviewing'],
  13. },
  14. options: {
  15. responsive: true,
  16. cutoutPercentage: 50,
  17. legend: {
  18. display: false,
  19. },
  20. },
  21. });
  22. })

}

展开查看全部

相关问题