Livewire 3中updated钩子修改变量后输入框未同步问题
Livewire 3中updated钩子更新变量后输入框不同步显示的问题
在Livewire 3环境下,通过updated钩子更新另一个wire:model绑定的变量时,视图中直接打印的变量值已经更新,但对应的绑定输入框却不显示新值。这套逻辑在Livewire 2中可以正常运行。
视图代码
{{ $customerCode }} <input wire:model.live="customerCode" type="text" id="customer_code" name="customer_code" class="form-control" placeholder="" /> <input type="text" wire:model.blur="name" class="form-control" placeholder="John Doe"/> {{-- 修改此输入框时会触发updatedName钩子,视图中上方的$customerCode已更新,但输入框未更新 --}}
组件代码
public function updatedName(){ $this->customerCode = 'random string';//generateUniqueUserCode($this->name); }
解决方法
方法1:手动触发属性变更通知
Livewire 3中,当在组件方法内更新属性后,对于使用.live修饰符的绑定,需要手动通知前端同步属性。在updatedName方法中添加notifyPropertyChanged调用:
public function updatedName(){ $this->customerCode = 'random string'; $this->notifyPropertyChanged('customerCode'); }
方法2:调整绑定修饰符
如果不需要实时同步customerCode输入框的内容(即不需要输入时立刻同步到组件),可以去掉.live修饰符,改用默认的wire:model,此时组件属性更新后输入框会自动同步:
<input wire:model="customerCode" type="text" id="customer_code" name="customer_code" class="form-control" placeholder="" />
方法3:触发组件全局刷新
如果前两种方法无效,可以直接触发组件刷新,强制同步所有属性到前端:
public function updatedName(){ $this->customerCode = 'random string'; $this->dispatch('$refresh'); }
内容的提问来源于stack exchange,提问作者Shubham Sahu
相关产品推荐
相关产品推荐

