I need some help with the Livewire Click function and loading a component into a foreach loop.
When I click the play button, the component is displayed in all items in the loop. But I would like that it is only displayed in this one item where the button was clicked.
I hope someone can help me with this problem.
Many thanks in advance.
seach-video.blade.php
@foreach ($searchResults as $item)
<div class="w-full mx-auto border rounded-md border-gray-300 shadow">
...
<div class="px-4">
<div class="mb-4 flex-1 space-y-4 py-1">
<h2 class="text-xl font-semibold overflow-ellipsis overflow-hidden">{{ $item['title'] }}
</h2>
<div class="space-y-2">
<p>
...
</p>
</div>
</div>
<div class="flex flex-wrap py-4">
<!-- Livewire Audio Player Component here -->
<div class="w-full">
<livewire:audio-player :wire:key="$item['id']">
</div>
<div wire:click="openPlayer('{{ $item['id'] }}')"
class="cursor-pointer border rounded font-semibold bg-blue-300 border-blue-600 px-4 py-2 mr-2 text-blue-600">
Play</div>
...
</div>
</div>
</div>
@endforeach
SearchVideo.php
class SearchVideo extends Component
{
....
public function loadSearchResults()
{
...
}
public function openPlayer($vid)
{
$this->emit('showPlayer', $vid)->to('audio-player');
}
public function closePlayer()
{
$this->emit('closePlayer')->to('audio-player');
}
public function render()
{
return view('livewire.search-video');
}
}
audio-player.blade.php
<div>
@isset($showPlayer)
player here {{ $videoId }}
@endif
</div>
AudioPlayer.php
class AudioPlayer extends Component
{
public $showPlayer;
public $videoId;
protected $listeners = ['showPlayer' => 'openPlayer', 'closePlayer' => 'closePlayer'];
public function openPlayer($vid)
{
$this->showPlayer = true;
$this->videoId = $vid;
}
public function closePlayer()
{
unset($this->showPlayer);
}
public function hydrate()
{
$this->dispatchBrowserEvent('contentChanged');
}
public function render()
{
return view('livewire.audio-player');
}
}