Laravel Livewire,如何通过单击将ID或数据传递到另一个组件

15

我有两个组件,分别是“Posts”和“Post”,“Posts”用于展示帖子列表,在点击图片后,我希望能够在另外一个组件中显示所点击的帖子的详细数据。

以下是“Posts”类和组件:

组件视图:


<div class="post" x-data="{open:false}">
  @foreach($posts as $post)
    <div>
      <h1>{{ $post->name }}</h1>
      <h3>{{ $post->body }}</h3>
      <img @click="open = !open" wire:click="showPost({{ $post->id }})" src="{{ $post->image }}" alt="">
    </div>
  @endforeach


<livewireL:post>

    </div>

组件类:

class Posts extends Component
{


  public $posts, $post;

  public function mount(){
    $this->posts = Post::all();

  }


  public function showPost($id){
    $post = Post::find($id);
    $this->post = $post;
  }

    public function render()
    {
        return view('livewire.posts');
    }
}

这是我想在此组件中展示所点击数据的文章组件和类,我尝试了$emit和许多文档,但没有结果。

我想要呈现数据的组件视图:



<div x-show="open">
  <h1>{{ $post->name }}</h1>
  <h3>{{ $post->body }}</h3>
  <img src="{{ $post->image }}">
</div>

我想要传递数据的类:

class Post extends Component
{

  public $post;



  public function mount($id)
  {
    $this->post = \App\Post::find($id);
  }



    public function render()
    {
        return view('livewire.post');
    }
}
2个回答

21

您需要使用事件来将数据从一个组件传递到另一个组件,如下所示。

组件A Blade:

  <img @click="open = !open" wire:click="showPost({{ $post->id }})" src="{{ $post->image }}" alt="">

组件 A 类:

public function showPost($id){
    $post = Post::find($id);
    $this->post = $post;
    $this->emit('newPost', $post->id);
  }

现在您可以像这样从其他Livewire组件中捕获该事件:

组件B类:

class Post extends Component
{

  public $post;

  protected $listeners = ['newPost'];

  public function mount($id)
  {
    $this->post = \App\Post::find($id);
  }

   public function render()
   {
        return view('livewire.post');
   }

   public function newPost($postId)
   {
       // here u have the id in your other component. 
   }
}

你也可以通过其他方式实现这个功能。你也可以从组件 blade 中传递 id,查看这里


谢谢兄弟,我还在犹豫是在 Laravel 中使用 React 还是 Livewire,但我正在尝试中,谢谢。 - Mehdi Yaghoubi
你最终使用了 Livewire 吗?哈哈 - CodeGuru
5
Livewire 在用户交互非常少的情况下很好用!但是,当您考虑到需要几千到数百万用户进行交互的大型应用程序时,为了保持良好的用户体验并确保服务器保持良好状态,您必须选择 React / Vue! - fahim152
你能传递一个对象而不是字符串或整数吗? - nclsvh

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接