You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 02:34:52