forked from livewire/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inline-scripts.blade.php
executable file
·61 lines (47 loc) · 1.91 KB
/
inline-scripts.blade.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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.
@component('components.code', ['lang' => 'html'])
@verbatim
<div>
<!-- Your components HTML -->
<script>
document.addEventListener('livewire:load', function () {
// Your JS here.
})
</script>
</div>
@endverbatim
@endcomponent
@component('components.warning')
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 <a href="https://laravel-livewire.com/docs/events/">here</a>)
@endcomponent
You can also push scripts directly onto Blade stacks from your Livewire component:
@component('components.code', ['lang' => 'javascript'])
@verbatim
<!-- Your component's view here -->
@push('scripts')
<script>
// Your JS here.
</script>
@endpush
@endverbatim
@endcomponent
### 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:
@component('components.code', ['lang' => 'javascript'])
@verbatim
<script>
document.addEventListener('livewire:load', function () {
// Get the value of the "count" property
var 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 ("foo") is emitted from this component
@this.on('foo', () => {})
})
</script>
@endverbatim
@endcomponent
> Note: the `@@this` directive compiles to the following string for JavaScript to interpret: "Livewire.find([component-id])"