【问题标题】:event listener not picking up Laravel Livewire emit from mount() method (but working when firing from blade)事件侦听器未从 mount() 方法接收 Laravel Livewire 发射(但在从刀片触发时工作)
【发布时间】:2020-11-19 16:15:27
【问题描述】:

我有nested Livewire components,其中“孩子”fires an event 到“父母”。
问题是从孩子的 (mount) 方法触发时它没有到达侦听器。
从子级触发事件时,侦听器可能还不可用?
它在从孩子的刀片上射击时确实有效,使用 wire:click="$emit(...)" 或全局 JavaScript。

我的设置类比:first 方法获取帖子,second 方法获取+管理评论,我想让first 知道页面上有多少 cmets,以便它可以更新计数器.这可以作为我获得评论的 mount() 的一部分来完成。

如何从孩子的 mount() 方法触发事件,和/或其他方式更合适?

First.php

protected $listeners = ['testEmit'];

public function testEmit() {
   Log::info("testEmit listener"); // only received when firing from blade
}

first.blade.php

@livewire('second')

Second.php

    public function buttonClick()
    {
        // works
        $this->emit('testEmit', 'Second (method buttonClick)');
    }

    public function mount()
    {
        // not working (is sent but not received)
        $this->emit('testEmit', 'Second (method mount)');
    }

    public function render()
    {
        // does not work (does work after buttonClick emit)
        $this->emit('testEmit', 'Second (method render)');

        return view('livewire.second')->layout('layouts.guest');
    }

second.blade.php

<div>
    <button wire:click="$emit('testEmit')"> <!-- this works fine -->
</div>
<div>
   <button wire:click="buttonClick">test (calls method)</button>
</div>
<script>
//  Livewire.emit('testEmit') // this works fine
</script>

更新:向 Second.php 和 second.blade.php 添加更多详细信息/示例

【问题讨论】:

  • 尝试在render() menthod 下发射。
  • 那行不通。它只会在调用方法后才在渲染中调用发射。我将更新上面的示例以显示详细信息。
  • 你有没有得到这个工作@wivku?我也是这种情况
  • 不,情况没有改变。

标签: laravel laravel-livewire


【解决方案1】:

对于将来遇到此问题的任何人,我发现此方法可行:

//在*.blade文件中

<script>
    window.addEventListener("DOMContentLoaded", function () {
        Livewire.emit("emit_to_parent");
    });
</script>

//在livewire组件中

protected $listeners = ["emit_to_parent"];

public function emit_to_parent()
{
    $this->emit("foo");
}

作为背景,这个问题解释了为什么它不起作用

Cannot emit events from mount method #598

【讨论】:

    【解决方案2】:

    在这种情况下,我建议只在一个函数中发出代码。

    public function mount()
    {
        $this->buttonClick();
    }
    
    public function render()
    {
        $this->buttonClick();
        return view('livewire.second')->layout('layouts.guest');
    }
    
    public function buttonClick()
    {
        $this->emit('testEmit', 'Second (method buttonClick)');
    }
    

    【讨论】:

    • 关键是当从 mount() 或 render() 直接或通过函数调用时,emit() 不起作用。所以,mount() 或 render() 中的 $this->buttonClick() 没有任何作用。
    猜你喜欢
    • 2021-01-14
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2021-07-21
    • 2013-05-19
    • 1970-01-01
    • 2015-12-18
    相关资源
    最近更新 更多