Laravel Livewire选择"其他"选项时动态添加文本输入框实现咨询
落地实现方案
1. 调整Livewire组件代码
在原有组件基础上新增3个公共属性,同时在切换经营类别时重置经营类型的选中值避免旧值残留,修改后完整代码如下:
namespace App\Http\Livewire; use App\Models\Classes; use App\Models\Section; use Livewire\Component; class Conditional extends Component { public $parents = []; public $children = []; // 新增三个属性存储选中值和其他类型输入内容 public $selectedBusinessKind = -1; public $selectedBusinessType = -1; public $otherBusinessType = ''; public function mount() { $this->parents = [ ['id' => -1, 'title' => 'Select type'], ['id' => 1, 'title' => 'Physical Store'], ['id' => 2, 'title' => 'Online Shop'], ]; } public function onSelectFirst($option) { // 切换经营类别时重置经营类型选中值 $this->selectedBusinessType = -1; switch($option) { case '-1': { $this->children = []; break; } case '1': { $this->children = [ ['id' => -1, 'title' => 'Please select'], ['id' => 1, 'title' => 'Restaurant'], ['id' => 2, 'title' => 'Fast Food'], ['id' => 3, 'title' => 'Cafe'], ['id' => 4, 'title' => 'Bar'], ['id' => 5, 'title' => 'Night club'], ['id' => 6, 'title' => 'Other'], ]; break; } case '2': { $this->children = [ ['id' => -1, 'title' => 'Please select'], ['id' => 7, 'title' => 'Clothes'], ['id' => 8, 'title' => 'Food Delivery'], ['id' => 9, 'title' => 'Other'], ]; break; } } } public function render() { return view('livewire.conditional'); } }
2. 调整Blade模板代码
给两个下拉框加上Livewire双向绑定,新增条件判断逻辑控制其他类型输入框的显示,修改后完整代码如下:
<div> <x-jet-label for="business_kind" value="{{ ('Type')}}" /> <select name="business_kind" id="business_kind" wire:model="selectedBusinessKind" wire:change="onSelectFirst($event.target.value)"> @foreach($parents as $option) <option value="{{ $option['id'] }}">{{ $option['title'] }}</option> @endforeach </select> <x-jet-label for="business_type" value="{{ ('Business type')}}"/> <select id="business_type" name="business_type" wire:model="selectedBusinessType" wire:loading.attr="disabled"> @foreach($children as $option) <option value="{{ $option['id'] }}">{{ $option['title'] }}</option> @endforeach </select> <!-- 新增其他经营类型输入框 --> @if(in_array($selectedBusinessType, [6,9])) <x-jet-label for="other_business_type" value="{{ ('其他经营类型')}}" /> <x-jet-input id="other_business_type" type="text" wire:model="otherBusinessType" name="other_business_type" required /> @endif </div>
使用说明
表单提交时,判断$selectedBusinessType的值是否为6或9:如果是则取$otherBusinessType的值作为最终经营类型,否则直接取$selectedBusinessType对应的枚举值即可。
内容的提问来源于stack exchange,提问作者Laravel Liwevire Question
相关产品推荐
相关产品推荐

