You're browsing the documentation for an old version of Livewire. Consider upgrading your project to Livewire 3.x.
Inline Scripts
Introduction
Livewire recommends that you use AlpineJS for most of your JavaScript needs, but it does support using <script>
tags directly inside your component's view.
1<div>2 <!-- Your components HTML -->3 4 <script>5 document.addEventListener('livewire:load', function () {6 // Your JS here.7 })8 </script>9</div>
Please note that your scripts will be run only once upon the first render of the component. If you need to run a JavaScript function later - emit the event from the component and listen to it in JavaScript as described here)
You can also push scripts directly onto Blade stacks from your Livewire component:
1<!-- Your component's view here -->2 3@push('scripts')4<script>5 // Your JS here.6</script>7@endpush
Using the @js
directive
If ever you need to output PHP data for use in Javascript, you can now use the @js
directive.
1<script>2 let posts = @js($posts)3 4 // "posts" will now be a JavaScript array of post data from PHP.5</script>
Accessing the JavaScript component instance
Because Livewire has both a PHP AND a JavaScript portion, each component also has a JavaScript object. You can access this object using the special @this
blade directive in your component's view.
Here's an example:
1<script> 2 document.addEventListener('livewire:load', function () { 3 // Get the value of the "count" property 4 var someValue = @this.count 5 6 // Set the value of the "count" property 7 @this.count = 5 8 9 // Call the increment component action10 @this.increment()11 12 // Run a callback when an event ("foo") is emitted from this component13 @this.on('foo', () => {})14 })15</script>
Note: the
@this
directive compiles to the following string for JavaScript to interpret: "Livewire.find([component-id])"
← Previous Topic
Laravel Echo
Next Topic →
Testing