Livewire 3集成Froala编辑器:刷新后编辑器消失问题解决求助
Livewire 3 中 Froala 编辑器刷新消失的解决办法
Livewire 组件刷新时会重新渲染 DOM,直接给编辑器容器绑定 wire:model 会导致编辑器实例被销毁,最终出现编辑器消失的问题,以下是具体解决方案:
方案一:手动同步数据 + 监听组件刷新
避免直接给编辑器容器加 wire:model,改用编辑器的内容变更事件手动同步数据,同时监听 Livewire 的刷新事件,确保编辑器实例在组件刷新后能重新初始化:
前端代码
<label class="block"> <p>body</p> <div id="editor" class="w-full h-96">{!! $body !!}</div> </label> <script> document.addEventListener('livewire:init', function () { // 初始化 Froala 编辑器 function initEditor() { if (FroalaEditor.getEditor('#editor')) return; new FroalaEditor('#editor', { // 此处添加你的编辑器配置项 events: { // 内容变化时同步到 Livewire 属性 'contentChanged': function () { Livewire.dispatch('update-body', { content: this.html.get() }); } } }); } // 首次初始化 initEditor(); // 组件刷新后重新初始化编辑器 Livewire.hook('message.processed', initEditor); }); </script>
Livewire 组件代码
class YourComponent extends Component { public $body; protected $listeners = ['update-body' => 'updateBody']; public function updateBody($data) { $this->body = $data['content']; } // 你的其他组件逻辑 }
方案二:使用 wire:ignore 指令
给编辑器容器添加 wire:ignore,告诉 Livewire 不要在组件刷新时重新渲染该元素,保留编辑器实例,但同样需要手动同步数据:
前端代码
<label class="block"> <p>body</p> <div id="editor" wire:ignore class="w-full h-96">{!! $body !!}</div> </label> <script> document.addEventListener('livewire:init', function () { const editor = new FroalaEditor('#editor', { events: { 'contentChanged': function () { Livewire.dispatch('update-body', { content: this.html.get() }); } } }); }); </script>
Livewire 组件代码
同方案一中的组件代码,通过 update-body 事件同步数据。
注意事项
- 确保 Froala 编辑器的 JS、CSS 文件已正确引入,且加载顺序在 Livewire 之后;
- 如果需要从后端初始化编辑器内容,直接在容器中输出
{!! $body !!}即可。
内容的提问来源于stack exchange,提问作者Mehdi Yaghoubi
相关产品推荐
相关产品推荐

