- Создание компонента
- Создание экземпляра
- Имя компонента
- Данные представления
- Атрибуты
- Пользовательское представление
- Условия отображения
- Методы по условию
- Рендеринг
- AlpineJs
Создание компонента
MoonShine реализует консольную команду для создания MoonShineComponent, которая уже реализует базовые методы для использования в админ-панели.
php artisan moonshine:component
php artisan moonshine:component
В результате будет создан класс NameComponent
, который является основой нового компонента. По умолчанию он располагается в директории app/MoonShine/Components
.
А также Blade-файл для компонента в директории resources/views/admin/components
.
Создание экземпляра
Метод make()
используется для создания экземпляра компонента.
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()];}//...
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()];}//...
Имя компонента
Метод name()
позволяет установить уникальное имя для экземпляра, через которое можно вызывать события компонента.
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()->name('my-component')];}//...
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()->name('my-component')];}//...
Данные представления
Метод viewData()
позволяет передать данные в шаблон компонента.
namespace App\MoonShine\Components;//...final class MyComponent extends MoonShineComponent{protected function viewData(): array{return [];}}//...
namespace App\MoonShine\Components;//...final class MyComponent extends MoonShineComponent{protected function viewData(): array{return [];}}//...
Атрибуты
Для экземпляра компонента можно указать атрибуты с помощью метода customAttributes()
.
customAttributes(array $attributes)
customAttributes(array $attributes)
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()->customAttributes(['class' => 'mt-4'])];}//...
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()->customAttributes(['class' => 'mt-4'])];}//...
Пользовательское представление
Когда необходимо изменить представление, используя fluent interface, можно использовать метод customView()
.
customView(string $customView)
customView(string $customView)
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()->customView('components.my-component')];}//...
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()->customView('components.my-component')];}//...
Условия отображения
Вы можете отображать компонент на основе условий, используя метод canSee()
.
canSee(Closure $callback)
canSee(Closure $callback)
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()->canSee(function(Request $request) {return $request->user('moonshine')->id === 1;})];}//...
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()->canSee(function(Request $request) {return $request->user('moonshine')->id === 1;})];}//...
Методы по условию
Метод when()
реализует fluent interface и выполнит обратный вызов, когда первый аргумент, переданный методу, будет оценен как истинный.
when($value = null, callable $callback = null)
when($value = null, callable $callback = null)
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()->when(fn() => request()->user('moonshine')->id === 1,fn($component) => $component->canSee(fn() => false))];}//...
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()->when(fn() => request()->user('moonshine')->id === 1,fn($component) => $component->canSee(fn() => false))];}//...
В функцию обратного вызова будет передан экземпляр компонента.
Второй обратный вызов может быть передан методу when()
, он будет выполнен, когда первый аргумент, переданный методу, будет ложным.
when($value = null, callable $callback = null, callable $default = null)
when($value = null, callable $callback = null, callable $default = null)
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()->when(fn() => request()->user('moonshine')->id === 1,fn($component) => $component->customView('components.my-component-admin'),fn($component) => $component->customView('components.my-component'))];}//...
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()->when(fn() => request()->user('moonshine')->id === 1,fn($component) => $component->customView('components.my-component-admin'),fn($component) => $component->customView('components.my-component'))];}//...
Метод unless()
является обратным методу when()
и выполнит первый обратный вызов, когда первый аргумент ложен, в противном случае будет выполнен второй обратный вызов, если он передан методу.
unless($value = null, callable $callback = null, callable $default = null)
unless($value = null, callable $callback = null, callable $default = null)
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()->unless(fn() => request()->user('moonshine')?->id === 1,fn($component) => $component->customView('components.my-component')fn($component) => $component->customView('components.my-component-admin'))];}//...
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()->unless(fn() => request()->user('moonshine')?->id === 1,fn($component) => $component->customView('components.my-component')fn($component) => $component->customView('components.my-component-admin'))];}//...
Рендеринг
Метод render()
позволяет получить отрендеренный компонент.
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()->render()];}//...
use App\MoonShine\Components\MyComponent;//...public function components(): array{return [MyComponent::make()->render()];}//...
AlpineJs
Мы также рекомендуем вам ознакомиться с AlpineJs и использовать всю мощь этого js-фреймворка.
Вы можете использовать его реактивность, давайте посмотрим, как удобно создать компонент:
<div x-data="myComponent"><script>document.addEventListener("alpine:init", () => {Alpine.data("myComponent", () => ({init() {},}))})</script>
<div x-data="myComponent"><script>document.addEventListener("alpine:init", () => {Alpine.data("myComponent", () => ({init() {},}))})</script>