РЕПЕТИТОР математика физика информатика
Для школьников и студентов. Подтягивание пробелов. ЦЭ, ЦТ, ОГЭ, ЕГЭ.
Идет набор на ЛЕТО. Жмите для подробностей:)
59 of 274 menu

Директива wire:bind:style

Директива wire:bind:style используется для динамического связывания CSS-стилей HTML-элемента со свойствами компонента Livewire. В значение директивы передаётся имя свойства компонента, содержащего строку со стилями, либо массив стилей. При изменении связанного свойства Livewire автоматически обновляет стиль элемента без перезагрузки страницы.

Синтаксис

<div wire:bind:style="styleProperty"> Content </div>

В качестве значения можно передавать строку со стилями или массив:

<div wire:bind:style="'background: red; color: white;'"> Content </div> <div wire:bind:style="['background' => 'red', 'color' => 'white']"> Content </div>

Пример

Давайте создадим компонент, в котором цвет фона блока будет изменяться по клику на кнопку:

<?php namespace AppLivewire; use LivewireComponent; class StyleDemo extends Component { public $bgColor = '#f0f0f0'; public function changeColor() { $colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#ffa502', '#a29bfe']; $this->bgColor = $colors[array_rand($colors)]; } public function render() { return view('livewire.style-demo'); } } ?>
<div> <div wire:bind:style="'background-color: ' . $bgColor . '; padding: 20px; border-radius: 8px; transition: background-color 0.3s;'" style="min-height: 100px;" > <p>Current background color: {{ $bgColor }}</p> </div> <button wire:click="changeColor" style="margin-top: 10px;"> Change Color </button> </div>

Результат выполнения кода:

<div> <div style="background-color: #4ecdc4; padding: 20px; border-radius: 8px; transition: background-color 0.3s; min-height: 100px;"> <p>Current background color: #4ecdc4</p> </div> <button style="margin-top: 10px;"> Change Color </button> </div>

Пример

Использование массива для управления несколькими стилями одновременно:

<?php namespace AppLivewire; use LivewireComponent; class BoxStyle extends Component { public $boxStyles = [ 'width' => '200px', 'height' => '200px', 'background' => '#3498db', 'border-radius' => '10px', 'transition' => 'all 0.5s' ]; public $textStyles = [ 'color' => 'white', 'font-size' => '18px', 'text-align' => 'center' ]; public function enlarge() { $this->boxStyles['width'] = '300px'; $this->boxStyles['height'] = '300px'; $this->boxStyles['background'] = '#e74c3c'; } public function reset() { $this->boxStyles = [ 'width' => '200px', 'height' => '200px', 'background' => '#3498db', 'border-radius' => '10px', 'transition' => 'all 0.5s' ]; } public function render() { return view('livewire.box-style'); } } ?>
<div> <div wire:bind:style="$boxStyles" style="display: flex; align-items: center; justify-content: center; margin: 20px 0;" > <span wire:bind:style="$textStyles"> Resizable Box </span> </div> <button wire:click="enlarge" style="margin-right: 10px;"> Enlarge </button> <button wire:click="reset"> Reset </button> </div>

Результат выполнения кода:

<div> <div style="display: flex; align-items: center; justify-content: center; margin: 20px 0; width: 300px; height: 300px; background: #e74c3c; border-radius: 10px; transition: all 0.5s;"> <span style="color: white; font-size: 18px; text-align: center;"> Resizable Box </span> </div> <button style="margin-right: 10px;"> Enlarge </button> <button> Reset </button> </div>

Пример

Динамическое изменение ширины элемента в зависимости от значения свойства:

<?php namespace AppLivewire; use LivewireComponent; class ProgressBar extends Component { public $progress = 30; public function increase() { if ($this->progress < 100) { $this->progress += 10; } } public function decrease() { if ($this->progress > 0) { $this->progress -= 10; } } public function render() { return view('livewire.progress-bar'); } } ?>
<div> <div style="width: 100%; background: #ecf0f1; border-radius: 10px; height: 30px; overflow: hidden;"> <div wire:bind:style="'width: ' . $progress . '%; background: linear-gradient(90deg, #2ecc71, #27ae60); height: 100%; transition: width 0.3s;'" ></div> </div> <p style="margin-top: 10px;">Progress: {{ $progress }}%</p> <button wire:click="increase" style="margin-right: 10px;"> Increase </button> <button wire:click="decrease"> Decrease </button> </div>

Результат выполнения кода:

<div> <div style="width: 100%; background: #ecf0f1; border-radius: 10px; height: 30px; overflow: hidden;"> <div style="width: 60%; background: linear-gradient(90deg, #2ecc71, #27ae60); height: 100%; transition: width 0.3s;"></div> </div> <p style="margin-top: 10px;">Progress: 60%</p> <button style="margin-right: 10px;"> Increase </button> <button> Decrease </button> </div>

Смотрите также

  • директиву wire:bind,
    которая связывает HTML-атрибуты со свойствами компонента
  • директиву wire:bind.class,
    которая динамически управляет CSS-классами элемента
  • директиву wire:model,
    которая привязывает поле ввода к свойству компонента
  • директиву wire:dirty,
    которая отслеживает изменения свойств компонента
Мы используем cookie для работы сайта, аналитики и персонализации. Обработка данных происходит согласно Политике конфиденциальности.
принять все настроить отклонить