8

我有两个组件 Posts 和 Post,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');
    }
}

这是我想在该组件中显示单击数据的Post 组件和类,我尝试了 $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');
    }
}
4

1 回答 1

9

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

组件 A 刀片:

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

你也可以通过其他方式实现。您可以从组件刀片传递 id,也可以检查一下

于 2020-03-13T07:33:39.570 回答