Livewire V3如何向子目录组件使用dispatchTo触发事件?
Livewire V3 中使用 $dispatchTo 触发非默认目录组件的事件
你可以通过两种方式正确调用 $dispatchTo 来触发目标组件的 show-customer-modal 事件:
方式一:使用组件别名(推荐)
你通过 php artisan make:livewire pages.customers.modal 创建组件时,Livewire 已经自动注册了这个点分隔格式的组件别名,直接使用它即可:
// 基础用法 $this->dispatchTo('pages.customers.modal', 'show-customer-modal'); // 如果需要传递参数 $this->dispatchTo('pages.customers.modal', 'show-customer-modal', [ 'customerId' => $customer->id, 'customerName' => $customer->name ]);
方式二:使用组件完整类名
如果更倾向于强类型的写法,可以直接传入组件的完整命名空间类名:
// 直接使用完整命名空间 $this->dispatchTo(\App\Livewire\Pages\Customers\Modal::class, 'show-customer-modal'); // 先引入命名空间再使用 use App\Livewire\Pages\Customers\Modal; $this->dispatchTo(Modal::class, 'show-customer-modal');
注意事项
- 确保目标组件
<livewire:pages.customers.modal />已经在当前页面中正确渲染,否则事件无法被组件监听到。 - 事件名
show-customer-modal需要在Pages\Customers\Modal组件中通过#[On('show-customer-modal')]注解或者$listeners属性进行监听。
内容的提问来源于stack exchange,提问作者MathieuB
相关产品推荐
相关产品推荐

