如何在 Livewire 中使用嵌套表单字段?

How to use Nested Form Fields in Livewire?

我有一个名为 project-form 的组件,我又在其中调用了另一个名为 search-users 的组件。问题是我无法从嵌套组件即 search-users.

中设置 ProjectForm 中的 $members 属性

据我所知,$members 必须在 SearchUsers.php 中进行设置,但我希望必须在 ProjectForm.php 中进行设置,以便我可以保存在数据库中。

项目-form.blade.php

<form wire:submit.prevent="submit">
   <input wire:model="name"/>
   <input wire:model="category"/>
   <input wire:model="target_date"/>

   @livewire('search-users')
</form>

ProjectForm.php

<?php

namespace App\Http\Livewire;

use App\Models\Project;
use Livewire\Component;

class ProjectForm extends Component
{

    public string $name = '';
    public string $category = '';
    public string $target_date = '';
    public array $members = [];
    
    protected $rules = [
        'name' => 'required',
        'category' => 'required',
        'target_date' => 'required',
    ];

    public function submit(){
        
        $validated = $this->validate();
        Project::create($validated);
        toastr()->success('Project Created Successfully');
    }

    public function render()
    {
        return view('livewire.project-form');
    }
}

搜索-users.blade.php

@foreach($users as $user)
    <label class="list-group-item ps-0 border-0 d-flex justify-content-between align-items-center">
        <div class="d-flex align-items-center">
            <img alt="{{ $user->name }}" src="{{ url('storage/'.$user->avatar) }}" width="35" class="me-3 rounded-circle mx-auto d-block">
            {{ $user->name }}
        </div>
        <input class="form-check-input me-1" wire:model.defer="members" type="checkbox" value="{{ $user->id }}">
    </label>
@endforeach

正如@Qirel 已经建议的那样,您应该使用 Livewire events

在您的搜索组件中,您可以发出事件 memebersFound 并将搜索中的成员作为参数传递(请参阅 Livewire Passing parameters in events),如下所示

$this->emit('membersFound', $membersFound);

然后,在您的 ProjectForm 组件中您应该监听这个事件

protected $listeners = [
  'membersFound' => 'addMembers'
];

public function addMembers(array $members)
{
  $this->members = $members;
}