我有一个有几个输入字段的表单,其中一些使用AlpineJSx-if
有条件地呈现,这些元素有wire:model
数据,但是当元素有条件地呈现时,模型绑定似乎不起作用。我试图在元素上打印变量,但它不起作用。没有x-if
,它工作良好。
<div class="form-check" >
<input class="form-check-input appearance-none rounded-full h-4 w-4 border border-gray-300 bg-white checked:bg-[#60D619] checked:border-[#60D619] focus:outline-none transition duration-200 mt-1 align-top bg-no-repeat bg-center bg-contain float-left mr-2 cursor-pointer" type="radio" id="company" wire:model="isCompany" @click="open = true" value="true">
<label class="form-check-label inline-block px-1 text-sm text-gray-600" for="company">
Yes, I'm a company.
</label>
</div>
<div class="form-check">
<input class="form-check-input appearance-none rounded-full h-4 w-4 border border-gray-300 bg-white checked:bg-[#60D619] checked:border-[#60D619] focus:outline-none transition duration-200 mt-1 align-top bg-no-repeat bg-center bg-contain float-left mr-2 cursor-pointer" type="radio" id="person" wire:model="isCompany" @click="open = false" value="false">
<label class="form-check-label inline-block px-1 text-sm text-gray-600" for="person">
No. I'm not a company.
</label>
</div>
<div class="py-1" x-show="open" x-transition>
<span class="px-1 text-sm text-gray-600">Company Name</span>
<input wire:model.lazy="companyName" placeholder="" type="text"
class="text-md block px-3 py-2 rounded-lg w-full
bg-white border-2 border-gray-300 placeholder-gray-600 shadow-md focus:placeholder-gray-500 focus:bg-white focus:border-gray-600 focus:outline-none">
</div>
<div class="py-1" x-show="!open" x-transition>
<span class="px-1 text-sm text-gray-600">User Name</span>
<input wire:model="name" placeholder="" type="text"
class="text-md block px-3 py-2 rounded-lg w-full
bg-white border-2 border-gray-300 placeholder-gray-600 shadow-md focus:placeholder-gray-500 focus:bg-white focus:border-gray-600 focus:outline-none">
</div>
<div class="py-1" x-show="!open" x-transition>
<span class="px-1 text-sm text-gray-600">First Name</span>
<input wire:model="fullName" placeholder="" type="text"
class="text-md block px-3 py-2 rounded-lg w-full
bg-white border-2 border-gray-300 placeholder-gray-600 shadow-md focus:placeholder-gray-500 focus:bg-white focus:border-gray-600 focus:outline-none">
</div>
当x-show
使用时,问题消失,但不清除不必要的输入字段。我不希望这些数据保存在数据库中。这是因为x-show
只切换元素的可见性,而x-if
完全从DOM中删除了元素吗?或者当使用x-show
切换可见性时,是否有方法重置输入字段的值?
x-if
确实删除了该元素,而x-show
只是隐藏了该元素。
wire:model
只工作,如果它加载与Livewire。否则Livewire不"知道"这些字段存在,因此不能添加事件侦听器来检测更改/输入等。因此,您需要执行@Bennett已经提到的操作,只隐藏输入,并清除字段。
您可以使用$wire直接清除输入。否则,您将不得不在输入字段上调度更改或输入事件(更改为惰性,输入为非惰性)。