【问题标题】:Emitting a js event to Livewire with data使用数据向 Livewire 发送 js 事件
【发布时间】:2021-01-29 16:45:24
【问题描述】:

我有一个组件,其中每一行都是一个单独的组件。我正在使用 Echo + Pusher 发出事件,并且我想将事件范围限定为仅刷新相关行。

文档中没有对此进行描述,但是在 this article(最后一个视频,约 8 分 30 秒)中,Caleb Porzio(Livewire 的创建者)有一个旧的(可能已经过时的)视频,这是通过添加相关 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 没有像您期望的那样在getListeners() 方法中定义吗?
  • 另外,如果你想使用 Laravel Echo,有一个特定的前缀。见laravel-livewire.com/docs/2.x/laravel-echo

标签: laravel eventemitter laravel-echo laravel-livewire


【解决方案1】:

我在我的侦听器数组中使用$this->monitorId

public function getListeners()
{
    return [
        "HitReceived:{$this->monitorId}" => 'refresh',
    ];
}

但是变量被声明为protected:

protected $monitorId;

我不太明白为什么这会导致我看到的错误,但是将其更改为 public 属性可以解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 2021-09-21
    相关资源
    最近更新 更多