【问题标题】:Laravel Livewire get current page IDLaravel Livewire 获取当前页面 ID
【发布时间】:2020-06-24 15:03:12
【问题描述】:

在一个视图中,我包含了一个这样的 livewire 组件:

<livewire:search-comments :post="$post">

如上图,我可以通过帖子。但问题是这只能在mount()上完成:

public function mount($post)
{
    $this->post = $post;
}

render(),我有:

$comments = $this->post->comments()
    ->where('comment', 'like', "%{$this->search}%")
    ->get()

问题是我需要在每次render() 调用时访问$post,因为搜索的 cmets 与用户当前所在的帖子相关联。我可以在隐藏字段中传递帖子 ID,但这感觉不是正确的(并且是安全的..?)解决方案。

【问题讨论】:

    标签: laravel laravel-livewire


    【解决方案1】:

    有多种方法可以实现这一点。就像您可以在用户尝试加载新帖子时发出事件一样。然后使用魔术方法 $refresh 刷新组件。

      protected $listeners = [
            'newPostLoad' => '$refresh',
        ];
    
    

    或者,

    您可以在尝试加载新帖子时传递帖子 ID。像这样:

    // as per your snippets above I assume ur blade has post collection which holds id for each posts.
    
    
    wire:click=loadNewPost(id) 
    

    然后你可以在 loadNewPost 函数中重置你的 $this->post。

    希望这会有所帮助。让我知道。我会再详细说明

    【讨论】:

    • 我从未意识到 $this->post 将始终保持同步,即使在第一次挂载之后也是如此。所以实际上没有必要实现这个,但你的答案仍然有效,并且可能在另一个相关场景中帮助其他人。
    • 是的,Livewire 中的一切都是反应式的。如果你有一点 Vue JS 知识,livewire 的一切对你来说都超级简单。
    猜你喜欢
    • 2014-04-16
    • 2011-05-07
    • 2012-02-08
    • 1970-01-01
    • 2012-12-04
    • 2018-06-14
    • 2022-11-02
    • 2013-04-17
    • 1970-01-01
    相关资源
    最近更新 更多