- Добавление
- Удаление
- Итеративные атрибуты
- Массовое изменение
- Объединение значений
- Добавление класса
- Добавление стиля
- Атрибуты для Alpine.js
Компоненты предлагают удобный механизм для управления HTML-классами, стилями и другими атрибутами, что позволяет более гибко настраивать их поведение и внешний вид.
Добавление
Метод setAttribute() добавляет или изменяет атрибут компонента.
setAttribute(string $name,string|bool $value)setAttribute(string $name,string|bool $value)
$name- название атрибута,$value- значение.
$component->setAttribute('data-id', '123');$component->setAttribute('data-id', '123');
Удаление
Метод removeAttribute() удаляет атрибут по его имени.
removeAttribute(string $name)removeAttribute(string $name)
$name- название атрибута.
$component->removeAttribute('data-id');$component->removeAttribute('data-id');
Итеративные атрибуты
Метод iterableAttributes добавляет атрибуты, необходимые для работы с итеративными компонентами.
iterableAttributes(int $level = 0)iterableAttributes(int $level = 0)
$level- уровень вложенности.
Массовое изменение
Метод customAttributes() добавляет или заменяет несколько атрибутов компонента.
customAttributes(array $attributes,bool $override = false)customAttributes(array $attributes,bool $override = false)
$attributes- массив добавляемых атрибутов,$override- ключ, который позволяет перезаписать существующие атрибуты.
$component->customAttributes(['data-role' => 'admin'], true);$component->customAttributes(['data-role' => 'admin'], true);
Объединение значений
Метод mergeAttribute() объединяет значение атрибута с новым значением, используя указанный разделитель.
mergeAttribute(string $name,string $value,string $separator = ' ')mergeAttribute(string $name,string $value,string $separator = ' ')
$name- название атрибута,$value- значение,$separator- разделитель.
$component->mergeAttribute('class', 'new-class');$component->mergeAttribute('class', 'new-class');
Добавление класса
Метод class() добавляет CSS-классы к атрибутам компонента.
class(string|array $classes)class(string|array $classes)
$classes- классы, которые необходимо добавить к компоненту.
$component->class(['btn', 'btn-primary']);$component->class(['btn', 'btn-primary']);
Также вы можете удалить класс или набор классов, добавленных ранее, по заданному паттерну.
$component->removeClass('btn-success');$component->removeClass('btn-success');
$component->removeClass('btn-(success|primary)');$component->removeClass('btn-(success|primary)');
Добавление стиля
Метод style добавляет CSS-стили к атрибутам компонента.
style(string|array $styles)style(string|array $styles)
$component->style(['color: red']);$component->style(['color: red']);
Атрибуты для Alpine.js
Для удобной интеграции с JavaScript-фреймворком Alpine.js, вы можно использовать методы установки соответствующих атрибутов.
x-data
Всё в Alpine начинается с директивы x-data.
Метод xData() определяет фрагмент HTML как компонент Alpine и предоставляет реактивные данные для ссылки на этот компонент.
xData(null|array|string $data = null)xData(null|array|string $data = null)
// title реактивная переменная внутриDiv::make([])->xData(['title' => 'Hello world'])// title реактивная переменная внутриDiv::make([])->xData(['title' => 'Hello world'])
x-data с указанием компонента и его параметров:
xDataMethod(string $method,...$parameters)xDataMethod(string $method,...$parameters)
Div::make([])->xDataMethod('some-component', 'var', ['foo' => 'bar'])Div::make([])->xDataMethod('some-component', 'var', ['foo' => 'bar'])
x-model
x-model связывание поля с реактивной переменной.
xModel(?string $column = null)xModel(?string $column = null)
Div::make([Text::make('Title')->xModel()])->xData(['title' => 'Hello world'])Div::make([Text::make('Title')->xModel()])->xData(['title' => 'Hello world'])
x-if
x-if скрывает поле, удаляя его из DOM.
xIf(string|Closure $variable,?string $operator = null,?string $value = null,bool $wrapper = true)xIf(string|Closure $variable,?string $operator = null,?string $value = null,bool $wrapper = true)
Div::make([Select::make('Type')->native()->options([1 => 1, 2 => 2])->xModel(),Text::make('Title')->xModel()->xIf('type', 1)])->xData(['title' = 'Hello world', 'type' => 1])// илиDiv::make([Select::make('Type')->options([1 => 1, 2 => 2])->xModel(),Text::make('Title')->xModel()->xIf(fn() => 'type==2||type.value==2')])->xData(['title' => 'Hello world', 'type' => 1])// если нужно скрыть поле без контейнераDiv::make([Select::make('Type')->native()->options([1 => 1, 2 => 2])->xModel(),Text::make('Title')->xModel()->xIf('type', '=', 2, wrapper: false)])->xData(['title' => 'Hello world', 'type' => 1])Div::make([Select::make('Type')->native()->options([1 => 1, 2 => 2])->xModel(),Text::make('Title')->xModel()->xIf('type', 1)])->xData(['title' = 'Hello world', 'type' => 1])// илиDiv::make([Select::make('Type')->options([1 => 1, 2 => 2])->xModel(),Text::make('Title')->xModel()->xIf(fn() => 'type==2||type.value==2')])->xData(['title' => 'Hello world', 'type' => 1])// если нужно скрыть поле без контейнераDiv::make([Select::make('Type')->native()->options([1 => 1, 2 => 2])->xModel(),Text::make('Title')->xModel()->xIf('type', '=', 2, wrapper: false)])->xData(['title' => 'Hello world', 'type' => 1])
x-show
x-show тоже самое что и x-if, но не удаляет элемент из DOM, а только скрывает.
xShow(string|Closure $variable,?string $operator = null,?string $value = null,bool $wrapper = true)xShow(string|Closure $variable,?string $operator = null,?string $value = null,bool $wrapper = true)
x-html
x-html вывод значения.
xDisplay(string $value,bool $html = true)xDisplay(string $value,bool $html = true)
Div::make([Select::make('Type')->native()->options([1 => 'Paid',2 => 'Free',])->xModel(),Number::make('Cost', 'price')->xModel()->xIf('type', '1'),Number::make('Rate', 'rate')->xModel()->xIf('type', '1')->setValue(90),Div::make()->xShow('type', '1')->xDisplay('"Result:" + (price * rate)'),])->xData(['price' => 0,'rate' => 90,'type' => '2',]),Div::make([Select::make('Type')->native()->options([1 => 'Paid',2 => 'Free',])->xModel(),Number::make('Cost', 'price')->xModel()->xIf('type', '1'),Number::make('Rate', 'rate')->xModel()->xIf('type', '1')->setValue(90),Div::make()->xShow('type', '1')->xDisplay('"Result:" + (price * rate)'),])->xData(['price' => 0,'rate' => 90,'type' => '2',]),