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

Laravel Livewire组件updated钩子更新description后name字段不生效问题

问题原因及解决方法

你遇到的name字段无法同步更新的问题,是双向绑定冲突导致的,可按以下步骤修复:

  • 移除视图中表单元素的原生value属性与默认内容:Livewire的wire:model会自动处理双向绑定的初始值、提交值,手动写的value属性、textarea标签内的默认内容会和绑定逻辑冲突,导致前端展示不更新。
    修改后的视图代码如下:
<div class="mt-4">
    <label class="block font-medium text-sm text-gray-700" for="description">{{ __('Description') }}</label>
    <textarea wire:model.lazy="description" 
    class="rounded-md shadow-sm border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 block mt-1 w-full"
    id="description" name="description" cols="100"
    rows="4"></textarea>
</div>
<div class="mt-4">
    <label class="block font-medium text-sm text-gray-700" for="name">{{ __('Name') }}</label>
    <input wire:model="name" id="name" type="text" name="name" 
    class="rounded-md shadow-sm border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 block mt-1 w-full"/>
</div>
  • 如果是编辑场景需要加载已有record的初始值,在组件中添加mount方法完成初始赋值即可,不要在视图层处理初始值:
// 加入组件类中
public function mount($record = null)
{
    $this->record = $record;
    if ($this->record) {
        $this->name = $this->record->name;
        $this->description = $this->record->description;
    }
}
  • 可选验证:如果修改后仍有问题,可先将textarea的wire:model.lazy改为wire:model测试是否是懒加载触发时机不符合你的预期,lazy模式只会在textarea失焦时才触发后台的updatedDescription方法,如果你需要实时输入触发,直接用wire:model即可。

内容的提问来源于stack exchange,提问作者Alexandru Popa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 17:15:02