Laravel Echo
Laravel Echo
Livewire与Laravel Echo完美搭配,可使用WebSocket在您的网页上提供实时功能。
此功能假定您已经安装了Laravel Echo,并且 window.Echo
对象在全局可用。 更多信息,请查看官方文档。
考虑以下Laravel事件:
class OrderShipped implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function broadcastOn()
{
return new Channel('orders');
}
}
假设您使用Laravel的广播系统触发此事件,如下所示:
event(new OrderShipped);
通常,您会像这样在Laravel Echo中监听此事件:
Echo.channel('orders')
.listen('OrderShipped', (e) => {
console.log(e.order.name);
});
但是,使用Livewire,您要做的就是在 $listeners 属性中注册它,并使用一些特殊的语法来指定它来自Echo。
use Livewire\Component;
class OrderTracker extends Component
{
public $showNewOrderNotification = false;
// 特殊语法: ['echo:{channel},{event}' => '{method}']
protected $listeners = ['echo:orders,OrderShipped' => 'notifyNewOrder'];
public function notifyNewOrder()
{
$this->showNewOrderNotification = true;
}
public function render()
{
return view('livewire.order-tracker');
}
}
现在,Livewire 将拦截从 Pusher 收到的事件,并采取相应的措施。 以类似的方式,您还可以收听广播到私人/状态频道的事件:
确保正确定义了身份验证回调。
use Livewire\Component;
class OrderTracker extends Component
{
public $showNewOrderNotification = false;
public $orderId;
public function mount($orderId)
{
$this->orderId = $orderId;
}
public function getListeners()
{
return [
"echo-private:orders.{$this->orderId},OrderShipped" => 'notifyNewOrder',
// Or:
"echo-presence:orders.{$this->orderId},OrderShipped" => 'notifyNewOrder',
];
}
public function notifyNewOrder()
{
$this->showNewOrderNotification = true;
}
public function render()
{
return view('livewire.order-tracker');
}
}