如何用Livewire动态添加输入字段?代码报错求解决
问题修复方案
1. 解决类名冲突
你的组件类命名为Test,同时在mount方法中调用Test::all(),这会导致PHP把Test解析为当前的Livewire组件类而非你的模型类,从而触发类型错误。解决方法二选一:
- 给组件类重命名,比如改为
TestForm - 调用模型时使用完整命名空间,比如
\App\Models\Test::all()
2. 统一数据类型
初始$tests定义为字符串数组[''],但mount方法中又赋值为模型集合,后续add方法添加字符串会导致数据类型混乱。如果是要动态添加输入框创建新记录,应让$tests保持为字符串数组(存储输入值);如果需要加载已有数据,要把模型的属性值提取到数组中。
3. 修正wire:model绑定
Blade模板中使用了wire:model="title.{{$index}}",但组件中未定义$title属性,应该绑定到tests.{{$index}},因为循环的是$tests数组。
4. 添加submit方法
表单使用了wire:submit.prevent="submit",但组件中缺少对应处理方法,需要添加该方法来完成表单提交逻辑。
修正后的PHP组件代码
namespace App\Http\Livewire; use Livewire\Component; use App\Models\Test; class TestForm extends Component { public $tests = ['']; public function mount() { // 如需加载已有数据,可取消注释以下代码 // $existingTitles = Test::all()->pluck('title')->toArray(); // $this->tests = $existingTitles ?: ['']; } public function add() { $this->tests[] = ''; } public function submit() { foreach ($this->tests as $testValue) { if (!empty(trim($testValue))) { Test::create(['title' => $testValue]); } } session()->flash('message', '操作成功'); $this->tests = ['']; } public function render() { return view('livewire.test-form'); } }
修正后的Blade视图代码
<div> @if(session()->has('message')) <div class="alert alert-success"> {{ session('message') }} </div> @endif <form wire:submit.prevent="submit"> @foreach($tests as $index => $test) <div class="mb-3"> <label class="form-label">标题</label> <input type="text" wire:model="tests.{{ $index }}" class="form-control @error('tests.'.$index) is-invalid @enderror" > @error('tests.'.$index) <div class="invalid-feedback">{{ $message }}</div> @enderror </div> @endforeach <button type="submit" class="btn btn-primary me-2">保存</button> </form> <button wire:click="add()" class="btn btn-secondary mt-2">添加更多</button> </div>
内容的提问来源于stack exchange,提问作者user15723984
相关产品推荐
相关产品推荐

