为什么我的 Laravel Livewire 事件发射不起作用?

Why is my Laravel Livewire event emission not working?

我有一个列出用户的简单 Livewire 组件:

class UserListComponent extends Component
{
    use WithPagination;

    protected $listeners = ['refreshComponent' => '$refresh'];

    public $search = '';
    public $orderBy = 'id';
    public $orderAsc = true;
    public $perPage = 10;

    public function render()
    {   
        return view('livewire.admin.user-list-component',[
            'users' => User::search($this->search)
                ->orderBy($this->orderBy, $this->orderAsc ? 'ASC' : 'DESC') 
                ->simplePaginate($this->perPage)
        ]);
    }
}

以及添加用户的组件:

public function addUser()
    {   
        // validate data
        $validatedData = $this->validate();

        // generate random password
        $bytes = openssl_random_pseudo_bytes(4);
        $password = bin2hex($bytes);
        
        // create user
        $user = User::create([
            'name' => $validatedData['name'],
            'email' => $validatedData['email'],
            'password' => Hash::make($password),
        ]);

        event(new Registered($user));

        // assign user role
        $user->attachRole('user');

        $this->emitTo('UserListComponent', 'refreshComponent');
    }

如您所见,在 addUser() 函数的末尾,我向 UserListComponent 发出了一个事件,并在该组件中设置了一个侦听器来刷新它,以便在添加用户时列表用户自动更新。但是,它不起作用。如果我手动刷新,我可以看到用户已添加到数据库并显示正常,但不会发生组件刷新,也不会抛出任何错误。

有什么想法吗?

据我所知,最好的方法是使用完整的 class 名称,而不是:

$this->emitTo('UserListComponent', 'refreshComponent');

你应该使用:

$this->emitTo(\App\Http\Livewire\UserListComponent:class, 'refreshComponent');

(如果您在其他命名空间中有 UserListComponent,当然更新命名空间)