我有一个表单,有几个输入字段,其中一些使用AlpineJS x-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
切换可见性时,是否有办法重置输入字段的值?
1条答案
按热度按时间xe55xuns1#
x-if
确实删除了元素,而x-show
只是隐藏了它。wire:model
只有在使用Livewire加载时才能工作。否则Livewire不“知道”这些字段的存在,因此无法添加事件侦听器来检测更改/输入等。因此,您需要执行@班尼特已经提到的操作,仅隐藏输入,并清除字段。你可以使用$wire直接清除输入,否则,你将不得不分派一个变更或者在输入域输入event(变更代表延迟,输入代表非延迟)。