Inline Scripts
AlpineJS is recommended for most of your JavaScript needs, but using <script>
tags directly inside component is perfectly acceptable.
<div>
...
<script>
document.addEventListener('wire:load', function () {
// Your JS here.
})
</script>
</div>
Each component has a JavaScript object. You can access this object using the special @this
directive in your component.
Here's an example.
Assuming you're dispatching and event after performing some updates in a action handler:
public function update(): void {
// My action code here...
$this->emitSelf('notifyUpdatedSuccess');
}
In your component template you can do:
<div>
...
<script>
document.addEventListener('wire:load', function () {
// Get the value of the "count" property.
let someValue = @this.count
// Set the value of the "count" property.
@this.count = 5
// Call the increment component action.
@this.increment()
// Run a callback when an event ("notifyUpdatedSuccess")
// is emitted from this component.
@this.on('notifyUpdatedSuccess', () => {
console.log('Successfully updated');
})
})
</script>
</div>
Another example using AlpineJs to display a Success message disappearing in 2.5 seconds.
<span
x-data="{ open: false }"
x-init="
@this.on('notifyUpdatedSuccess', () => {
if (open === false) setTimeout(() => { open = false }, 2500);
open = true;
})
"
x-show="open"
style="display: none;"
class="text-green-500 mr-5"
>Updated!</span>
Note: the
@this
directive compiles to the following string for JavaScript to interpret: "Wire.find([component-id])"