-
-
Save marufsharia/7667f1d3d121d42080d3e2b22791b5ac to your computer and use it in GitHub Desktop.
Livewire Tagify Component
This file contains hidden or 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/tagify@3.11.1/dist/tagify.min.css"> | |
| @endpush | |
| @push('scripts') | |
| <script src="https://cdn.jsdelivr.net/npm/@yaireo/tagify@3.11.1/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 hidden or 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