-
-
Save MACscr/2aa36ef77a4b6252cdc46102ed32bbcd to your computer and use it in GitHub Desktop.
Livewire Tagify Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div wire:ignore class="mb-4"> | |
<label class="label" for="tagify"> | |
Tags | |
</label> | |
<input | |
type="text" | |
id="tagify" | |
class="shadow-sm appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight" | |
> | |
</div> | |
@push('styles') | |
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@yaireo/[email protected]/dist/tagify.min.css"> | |
@endpush | |
@push('scripts') | |
<script src="https://cdn.jsdelivr.net/npm/@yaireo/[email protected]/dist/tagify.min.js"></script> | |
<script> | |
document.addEventListener("DOMContentLoaded", function(event) { | |
var input = document.getElementById('tagify') | |
var tagify = new Tagify(input, { | |
whitelist : [ | |
@foreach($tags as $tag) | |
'{{ $tag }}'@if(! $loop->last), @endif | |
@endforeach | |
] | |
}) | |
input.addEventListener('change', onChange) | |
function onChange(e){ | |
@this.call('changeTags', e.target.value) | |
} | |
}) | |
</script> | |
@endpush |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Livewire; | |
use App\Models\Tag; | |
use Illuminate\View\View; | |
use Illuminate\Contracts\View\Factory; | |
use Illuminate\Contracts\Container\BindingResolutionException; | |
use Livewire\Component; | |
class Tagify extends Component | |
{ | |
/** @var array */ | |
public array $tags; | |
/** | |
* mount. | |
* | |
* @param array $tags | |
* @return void | |
*/ | |
public function mount(?array $tags = []): void | |
{ | |
$this->tags = $tags; | |
} | |
/** | |
* change tags. | |
* | |
* @param string $tags | |
* @return void | |
*/ | |
public function changeTags(string $tags): void | |
{ | |
if (empty($tags)) { | |
return; | |
} | |
$changed = collect(json_decode($tags))->pluck('value')->toArray(); | |
$this->emitUp('changeTags', $changed); | |
} | |
/** | |
* render. | |
* | |
* @return View|Factory | |
* @throws BindingResolutionException | |
*/ | |
public function render() | |
{ | |
$this->tags = $this->tags ?: Tag::all()->pluck('name')->toArray(); | |
return view('livewire.tagify', [ | |
'tags' => $this->tags, | |
]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment