laravel livewire, how to pass the id or data to another component by click

随声附和 提交于 2020-03-21 20:57:12

问题


I have two components Posts and Post, Posts show the posts and by clicking the image I want to show the data of clicked post in another component.

Posts class and component down below:

Component View:


<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>

Component Class:

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');
    }
}

and this is the Post component and class that I want to show the clicked data in this component, I have tried $emit and many as documentation but no result.

Component view which I want to render that data:


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

Class which I want to pass data:

class Post extends Component
{

  public $post;



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



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

回答1:


You have to use events to pass data from one component to another component like below.

Component A Blade:

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

Component A Class:

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

you can now catch that event from other livewire component like this:

Component B Class:

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. 
   }
}

you can achieve this other way also. You can pass the id from your component blade as well check this out.



来源:https://stackoverflow.com/questions/60650712/laravel-livewire-how-to-pass-the-id-or-data-to-another-component-by-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!