Livewire 및 ChartJs
기대치는 다음과 같습니다.
Change the filter, will update chart.
쉬운 것 같죠? TLDR;
1 부
간단한 필터를 준비합니다.
php artisan make:livewire Filter
Filter 클래스:<?php
namespace App\Http\Livewire\Dashboard;
use Livewire\Component;
class Filter extends Component
{
public $selectedOrganization = null;
public function onOrganizationChange()
{
$this->emit('organization-selected', $this->selectedOrganization);
}
public function render()
{
return view('livewire.filter');
}
}
Livewire 보기 파일:
<div>
<div class="flex justify-end mt-4 px-4 w-full">
<div class="w-1/4">
<x-select wire:model.defer="selectedOrganization" wire:change="onOrganizationChange">
@foreach (organizations() as $organization)
<option value="{{ $organization->uuid }}">{{ $organization->name }}</option>
@endforeach
</x-select>
</div>
</div>
</div>
organizations() 도우미가 다음을 수행한다고 가정합니다.<?php
use App\Models\Organization;
if (! function_exists('organizations')) {
function organizations()
{
return Organization::orderBy('name')->get();
}
}
이제
Filter Livewire 구성요소를 완성했습니다.기본값으로 사용
resources/views/dashboard.blade.php:<x-app-layout>
<div class="min-h-full">
@livewire('filter')
</div>
</x-app-layout>
2 부
다음으로 차트를 표시하는 구성 요소입니다.
php artisan make:livewire Chart
Livewire 차트 블레이드 파일을 업데이트해 보겠습니다.
@once
@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
@endpush
@endonce
@push('scripts')
<script>
const chart = new Chart(
document.getElementById('chart'), {
type: 'line',
data: {
labels: @json($labels),
datasets: @json($dataset)
},
options: {
plugins: {
legend: {
position: 'bottom'
}
},
responsive: true,
scales: {
x: {
stacked: true,
},
y: {
stacked: true
}
}
}
}
);
Livewire.on('updateChart', data => {
chart.data = data;
chart.update();
});
</script>
@endpush
<x-panel class="bg-white p-4 mx-4 mt-4">
<div>
<canvas id="chart"></canvas>
</div>
</x-panel>
여기에는 몇 가지 일이 있습니다.
@once는 ChartJ를 전체 앱에 한 번만 포함하는 데 사용합니다. labels 및 datasets의 초기화는 @json 블레이드 지시문을 통해 동적으로 설정됩니다. 이는 백엔드에서 동적이고 구성 가능한 차트 개체의 초기 로드 및 구성을 단순화하기 위한 것입니다. Livewire.on는 단순히 updateChart 이벤트를 듣습니다. 듣고 있으면 차트를 업데이트합니다. 여기에서 데이터를 보내야 합니다. 그런 다음
Chart 클래스:<?php
namespace App\Http\Livewire\Dashboard;
use App\Models\Organization;
use Livewire\Component;
class Activity extends Component
{
public array $dataset = [];
public array $labels = [];
public Organization $organization;
protected $listeners = [
'organization-selected' => 'organizationSelected',
];
public function organizationSelected(string $uuid)
{
$this->organization = Organization::whereUuid($uuid)->first();
$labels = $this->getLabels();
$dataset = [
[
'label' => 'Logged In',
'backgroundColor' => 'rgba(15,64,97,255)',
'borderColor' => 'rgba(15,64,97,255)',
'data' => $this->getRandomData(),
],
];
$this->emit('updateChart', [
'datasets' => $dataset,
'labels' => $labels,
]);
}
public function mount()
{
$this->labels[] = $this->getLabels();
$this->dataset = [
[
'label' => 'Logged In',
'backgroundColor' => 'rgba(15,64,97,255)',
'borderColor' => 'rgba(15,64,97,255)',
'data' => $this->getRandomData(),
],
];
}
private function getLabels()
{
$labels = [];
for ($i = 0; $i < 12; $i++) {
$labels[] = now()->subMonths($i)->format('M');
}
return $labels;
}
private function getRandomData()
{
$data = [];
for ($i = 0; $i < count($this->getLabels()); $i++) {
$data[] = rand(10, 100);
}
return $data;
}
public function render()
{
return view('livewire.dashboard.activity');
}
}
우리가 살펴볼 유일한 것은 데이터가 채워지는 방식입니다. 선택한 조직에서
Filter에서 발생하고 Chart 메서드의 organizationSelected 클래스에서 받은 이벤트입니다.Chart는 새로운 데이터 세트를 채웁니다.이 경우 패스 12개월에 대한 데이터를 무작위로 생성합니다.
12개월 동안의 로그인 데이터 패턴을 보고 있다고 가정합니다.
그런 다음 마지막 부분인 다음 코드 조각은 데이터 세트 및 랩과 함께 이벤트를 전달합니다.
따라서
Livewire.on()에서 새 데이터 세트를 수신하고 새 차트를 렌더링합니다.$this->emit('updateChart', [
'datasets' => $dataset,
'labels' => $labels,
]);
결론
요점은 Livewire의 Event & Listener입니다.
프런트엔드 측에서 Livewire 수신기를 구성합니다.
Livewire.on('updateChart', data => {
chart.data = data;
chart.update();
});
그리고 새 데이터를 전달하기 위해 Livewire 백엔드 측에서 이벤트를 내보냅니다.
$this->emit('updateChart', $data);
이 두 가지 핵심 사항을 통해 사람들이 Livewire를 사용하여 동적 차트로 작업하는 데 도움이 되기를 바랍니다.
Reference
이 문제에 관하여(Livewire 및 ChartJs), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/nasrulhazim/livewire-chartjs-3ch5텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)