You're browsing the documentation for an old version of Livewire. Consider upgrading your project to Livewire 3.x.

Inline Scripts

Although Livewire should reduce the amount of JavaScript you need to write in your applications, there are certain places where JavaScript is still very much necessary. Therefore, it is important that Livewire provides clear techniques to utilize JavaScript in your Livewire components.

The simplest way to add some JavaScript functionality to a component is in a vanilla-js inline script tag inside the component. The best way to do this is using Blade stacks. This way you won't block DOM rendering in the browser, because your JavaScript will be grouped and rendered in the proper place.

Setting up a "scripts" stack

Declare a @stack('scripts') inside your Blade layout file.

        
1...
2 @livewireScripts
3 @stack('scripts')
4</body>

Pushing to the scripts stack

Now, from your component's Blade view, you can push to the scripts stack:

        
1<div>
2 <!-- Your components HTML -->
3</div>
4 
5@push('scripts')
6<script type="text/javascript">
7 document.addEventListener('DOMContentLoaded', function () {
8 // Your JS here.
9 })
10</script>
11@endpush
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)

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...
2 
3@push('scripts')
4<script type="text/javascript">
5 document.addEventListener('DOMContentLoaded', function () {
6 // Get the value of the "count" property
7 var someValue = @this.get('count')
8 
9 // Set the value of the "count" property
10 @this.set('count', 5)
11 
12 // Call the increment component action
13 @this.call('increment')
14 
15 // Run a callback when an event ("foo") is emitted from this component
16 @this.on('foo', () => {})
17 })
18</script>
19@endpush

Note: the @this directive compiles to the following string for JavaScript to interpret: "window.livewire.find([component-id])"

← Previous Topic Laravel Echo
Next Topic → Testing