laravel-8 - 触发事件并重新渲染组件后,Livewire 加载 javascript
问题描述
在我看来,当我有一个内联 javascript 被推送到布局中的堆栈时,我遇到了问题。这里的问题是当我的事件被触发时
<button type="button" class="form-icon" wire:click="changeTrainingType">
<i class="fa fa-exchange-alt"></i>
</button>
组件正在重新呈现,我的 javascript 没有被执行(在文档中它说 JS 只执行一次)你如何处理?
这是我的控制器
<?php
namespace App\Http\Livewire\Profile\Administration;
use Livewire\Component;
class CreateWorkoutsController extends Component
{
public bool $weeklyTrainingType = false;
protected $listeners = ['changeTrainingType'];
public function changeTrainingType()
{
$this->weeklyTrainingType = !$this->weeklyTrainingType;
}
public function render()
{
return view('livewire.profile.administration.workouts.create')
->extends('layouts.auth');
}
}
还有我的 JS
<script src="{{ url('js/ckeditor.js') }}"></script>
<script src="{{ url('libs/js/app.js') }}"></script>
<script>
document.addEventListener('livewire:load', function () {
console.log('here');
Livewire.on('changeTrainingType', event => {
alert('A post was added with the id of: ');
})
flatpickr('#event-date', {
enableTime: true,
minDate: 'today',
dateFormat: "Y-m-d H:i",
time_24hr: true,
});
flatpickr('.time-picker', {
mode: 'multiple',
enableTime: true,
dateFormat: "w H:i",
time_24hr: true
});
ClassicEditor.create(document.querySelector('#description'))
.then(editor => {
editor.editing.view.change(writer => {
writer.setStyle('height', '400px', editor.editing.view.document.getRoot())
})
})
.catch(error => {
console.error(error);
});
});
</script>
解决方案
当您单击按钮时,它会分派一个“方法”类型的事件,一旦您像 wire:click 指令一样定义它。在这种情况下,您不需要监听器。但是如果你想挂钩这个方法调用,你可以这样做:
document.addEventListener("DOMContentLoaded", () => {
Livewire.hook('message.sent', (message,component) => {
if (message.updateQueue[0].method === 'changeTrainingType') {
alert('there was a call to this method');
}
}
}
否则,wire:click="name_method" 使用 wire:click="$emit('name_of_event')" 并使用 listener 属性来挂钩它。