Livewire模态框表单为何实时触发updated?需仅提交时触发
问题
我在模态框中使用Livewire表单,目前输入框按键时会触发updated方法,但我需要仅在提交表单时才触发验证逻辑。查文档得知默认应该只在提交时触发验证,我已经试过wire:model.lazy和wire:submit.prevent,但问题依然存在。
代码示例
Livewire组件后端代码
public $title; public $quantity; public $note; protected $rules = [ 'title' => 'required|min:5', 'quantity' => 'integer', 'note' => '' ]; public function render() { return view('livewire.popups.add-product-form'); } public function updated($propertyName) { $this->validateOnly($propertyName); } public function save(Service $service) { $data = $this->validate(); $product = $service->store($data); $this->dispatchBrowserEvent('product-saved', ['action' => 'created']); $this->resetForm(); $this->emitTo('main', 'triggerRefresh'); } public function resetForm() { $this->title = null; }
前端Blade视图代码
<form wire:submit="save"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title"> <div> <input type="text" class="form-control" id="title" name="title" wire:model="title" placeholder="Продукт"> {{-- @error('title') <span class="text-danger">{{ $message }}</span> @enderror --}} </div> <div> <input type="number" class="form-control" id="quantity" name="quantity" wire:model="quantity" placeholder="1" value="1"> </div> </h5> </div> <div class="modal-body"> <div class="form-floating"> <textarea class="form-control" placeholder="Leave a comment here" id="note" name="note" wire:model="note"></textarea> <label for="note">Add Comment</label> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary">Создать</button> </div> </div> </form>
解决方法
核心原因:你主动定义了
updated方法,并且在里面调用了validateOnly($propertyName),这个方法会在Livewire的属性每次更新时(包括输入框按键同步数据时)自动执行,这就是实时触发验证的根源。最简单的解决方案:直接移除
updated方法。你的save方法里已经调用了$this->validate(),这会在表单提交时执行完整的规则验证,完全满足需求。可选优化(减少不必要的AJAX请求):如果想避免输入框每按键一次就同步数据到后端,可以给所有
wire:model加上.lazy修饰符,比如:<input type="text" class="form-control" id="title" name="title" wire:model.lazy="title" placeholder="Продукт"> <input type="number" class="form-control" id="quantity" name="quantity" wire:model.lazy="quantity" placeholder="1" value="1"> <textarea class="form-control" placeholder="Leave a comment here" id="note" name="note" wire:model.lazy="note"></textarea>这样数据只会在输入框失去焦点时同步到后端,进一步减少请求次数,但即使不加,只要移除
updated方法,也不会触发实时验证。
内容的提问来源于stack exchange,提问作者Женя Веденин
相关产品推荐
相关产品推荐

