You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Livewire集成Trix编辑器:数据库内容无法回显求助

问题分析与修复步骤

1. 修复Livewire组件的挂载逻辑

你当前的mount方法每次都会创建一个空的WhyMe实例,完全没有读取数据库中已保存的记录,这是刷新后编辑器内容消失的核心原因。修改为优先加载已有数据:

public function mount(): void
{
    // 按业务逻辑获取目标记录,示例为取第一条;多记录场景可根据ID/条件查询
    $this->whyMe = WhyMe::first() ?? $this->makeBlankWhyMe();
}

2. 修正wire:model拼写错误

调用组件时的wire:model.lozy是拼写错误,改为正确的wire:model.lazy:

<x-rich-text wire:model.lazy="whyMe.description" id="description" :initial-value="$whyMe->description" />
<x-input-error for="whyMe.description" class="mt-2"/>

3. 优化富文本组件的ID与数据同步

当前Trix编辑器的隐藏input固定为id="x",会导致多编辑器冲突,且无法同步Livewire更新后的数据。修改组件如下:

@props(['initialValue' => ''])

<div
    class="rounded-md shadow-sm col-span-6"
    wire:ignore
    {{ $attributes }}
    x-data="{ value: @entangle($attributes->wire('model')).defer }"
    x-init="
        // 初始化时加载初始内容
        document.getElementById('{{ $id }}').value = value;
        document.querySelector('trix-editor[input={{ $id }}]').editor.loadHTML(value);
        // 监听Livewire全局更新事件,同步最新数据
        window.addEventListener('livewire:update', () => {
            document.getElementById('{{ $id }}').value = value;
            document.querySelector('trix-editor[input={{ $id }}]').editor.loadHTML(value);
        });
    "
    @trix-blur="value = $event.target.value; $dispatch('change')"
>
    <input id="{{ $id }}" value="{{ $initialValue }}" type="hidden">
    <trix-editor input="{{ $id }}" class="form-textarea block w-full transition duration-150 ease-in-out sm:text-sm sm:leading-5"></trix-editor>
</div>

4. 补充保存逻辑(若未实现)

如果组件还没有保存方法,添加以下代码完成数据持久化:

public function save()
{
    $this->validate();
    $this->whyMe->save();
    session()->flash('message', '内容保存成功');
}

在视图中添加保存按钮:

<button wire:click="save" class="mt-4 px-4 py-2 bg-blue-500 text-white rounded">保存</button>

内容的提问来源于stack exchange,提问作者kristi tanellari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 21:30:59