In the livewire component, I have the script tag:
<script>
{!! $script !!}
</script>
Let's say the $script
variable contains console.log('test');
It is executed once - no surprise documentation explains this. The recommendation is to emit a custom event and listen to it, but the problem is that it does not work with code in a variable. In other words, this works:
<script>
document.addEventListener('custom-event', () => {
console.log('test');
})
</script>
but this does not:
<script>
document.addEventListener('custom-event', () => {
{!! $script !!}
})
</script>
Any idea how to solve this?
CodePudding user response:
try this
in component
public $foo;
$this->dispatchBrowserEvent('custom-event', ['foo' => $this->foo]);
in view
<script>
window.addEventListener('custom-event', event => {
alert('here value foo: ' event.detail.foo);
console.log(event.detail.foo);
})
</script>
CodePudding user response:
Try this ->
<script>
document.addEventListener('custom-event', () => {
{!! json_encode($script) !!}
})
</script>
I hope it was helpfull! :)