问题描述
我有一个组件,其中每一行都是一个单独的组件。我正在使用 Echo + Pusher 发出一个事件,我想将事件范围限定为仅刷新相关行。
文档中未对此进行描述,但 Caleb Porzio(Livewire 的创建者)在 this article(最后一个视频,约 8 分钟 30 秒)中有一个旧的(可能已经过时的)视频,通过添加将相关 ID 添加到事件名称中。
在我的 livewire 模型中,我有:
public function getListeners()
{
return [
"HitReceived:{$this->monitorId}" => 'refresh',];
}
在我的 JS 中,我有:
Livewire.emit('HitReceived:' + data.monitorId);
我可以在控制台中看到设置了 data.monitorId
。当我用 id #1 触发一个事件时,我收到一个 500 错误:
ERROR: Undefined array key "HitReceived1" {"userId":1,"exception":"[object] (ErrorException(code: 0):
Undefined array key \"HitReceived1\" at /vendor/livewire/livewire/src/ComponentConcerns/ReceivesEvents.PHP:72)
(如果我没有将我的事件范围限定到特定的模型实例,这一切都有效,但随后一切都会刷新。)
解决方法
我在我的听众数组中使用了 $this->monitorId
:
public function getListeners()
{
return [
"HitReceived:{$this->monitorId}" => 'refresh',];
}
但是变量被声明为protected
:
protected $monitorId;
我不太明白为什么这会导致我看到的错误,但将其更改为 public
属性解决了该问题。