Component interaction
Magewire bindings
Magewire provides a special attribute syntax to declare magic bindings.
These bindings are declared as HTML element attributes that start with the keyword wire:
.
For example:
If you are familiar with Alpine.js, you might recognize it looks similar to the binding <button x-on:click="...">Click me!</button>
.
However, there is one important difference.
In the case of wire:*
bindings they are not used to call a JavaScript functions, but instead, they will trigger an interaction with the PHP $magewire
component!
The most common bindings are
wire:click="foo"
Listens for aclick
event and calls thefoo
method of the component.wire:foo="bar"
Listens for a browser event calledfoo
and calls thebar
method of the component.
(You can listen for any browser DOM event - not just those fired by Magewire!).wire:model="foo"
Assuming$foo
is a public property on the component class, every time an input element with this directive is updated, the$magewire
property value is synchronized.wire:model.lazy="foo"
Lazily syncs the input with its corresponding component property at rest.wire:init="foo"
Calls thefoo
method of the component immediately after it renders on the page.
A full list of all bindings is available in the Livewire documentation.
Binding syntax example
With the binding, the PHP method registerClick
on the Magewire component will be executed when the visitor clicks the button.
"Magic" actions
Magewire provides a number of magic JavaScript functions that can be used to interact with compoment properties.
-
$set()
Use the$set
function to update a property of a Magewire component.
Note that$set
is NOT a PHP variable! It is more accurate to think of it as a JavaScript function that triggers that Ajax call to update the Magewire component property. -
$toggle()
Like$set()
, except that it only takes the name of a boolean property and toggles the property value. -
$refresh()
Request and render a new version of the component from the server. -
$emit()
Broadcast a message to all components that have subscribed to it. See Subscribing toemit
messages" for more information. -
$emitTo()
Send a message to a specific component. See Subscribing toemit
messages for more information onemit
.
Updating properties
For the following examples, let's assume we are working with a Magewire component with a property $isSubscribed
.
If a property update happens as the main effect of user interaction, the magic $set()
action is the most common way to update a property.
If the update happens inside a PHP function, simply assign the new property value:
// If the property is set inside of a component method (the usual case)
$this->isSubscribed = true;
// If the code is not in a component method:
$magewireComponent->isSubscribed = false;
Magewire components do NOT provide magic setter methods (only magic get
ters and has
ers).
Use direct property assignment instead: $this->foo = 123
.