【问题标题】:Laravel Livewire emit does not refresh the component data [duplicate]Laravel Livewire 发射不刷新组件数据[重复]
【发布时间】:2021-05-12 00:35:58
【问题描述】:

当单击按钮将数据传递给另一个组件时,我正在从我的 Livewire 组件调度一个事件。

public function updateSongs(int $index)
{
    $this->dispatchBrowserEvent('audio:updated', ['songs' => $this->albums[$index -1]['songs']]);
}

我的其他组件像这样监听这个事件

window.addEventListener('audio:updated', event => {
   const songs = event.detail.songs; // console.log shows expected data
   Livewire.emit('songsUpdated', songs);
});

然后我有一个监听器,它附加到一个将歌曲更新为新歌曲的函数:

class AudioPlayer extends Component
{
    public array $songs = [];
    protected $listeners = ['songsUpdated' => 'updateSongs'];

    protected function getListeners(): array
    {
        return ['songsUpdated' => 'updateSongs'];
    }

    public function render()
    {
        return view('livewire.audio-player', [
            'songs' => $this->songs,
        ]);
    }

    public function updateSongs(array $json)
    {
        $this->songs = $json;
    }
}

AudioPlayer 首次渲染时:

@livewire('audio-player', ['songs' => [
    [
        'id' => 1,
         'name' => '4x4',
         'artist' => 'Young T ft Bugsey',
         'cover' => 'https://i1.sndcdn.com/artworks-000237133916-4rd8mi-t500x500.jpg',
         'duration' => '3:42',
    ],
]])

它可以很好地加载数据。但是,当听众通过发出新的给定歌曲执行函数并更新$this->songs时 - 页面不会改变,组件不会用新数据刷新。

我做了一个var_dump($json),当我检查网络选项卡时,这给了我预期的结果。任何人都可以帮助我在这里缺少什么吗?

【问题讨论】:

标签: javascript php laravel laravel-livewire


【解决方案1】:

尝试重新渲染

public function updateSongs(array $json)
{
    $this->songs = $json;
    $this->render();
}

【讨论】:

  • 对不起,没有提到我试过这个。然后我也尝试了return $this->render();,但也没有用。我发现 Livewire 期望组件位于一个 <div> 内,因为我的实际组件包含多个,这就是它没有渲染的原因。我将标记为重复哪个问题解决了我的问题。
猜你喜欢
  • 2022-06-11
  • 2020-06-09
  • 1970-01-01
  • 2021-09-26
  • 2021-04-16
  • 2021-05-11
  • 2021-03-31
  • 1970-01-01
  • 2022-11-14
相关资源
最近更新 更多