【问题标题】:laravel livewire, how to pass the id or data to another component by clicklaravel livewire,如何通过单击将 id 或数据传递给另一个组件
【发布时间】:2020-06-24 07:17:19
【问题描述】:

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

【问题讨论】:

    标签: laravel laravel-livewire


    【解决方案1】:

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

    组件 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,也可以检查 this

    【讨论】:

    • 谢谢兄弟,还是想在 Laravel 中使用 React 或 Livewire,但是尝试,tkx
    • 那么你最终选择了 livewire 吗?哈哈
    • Livewire 在用户交互非常少的情况下非常好用!但是当你想到有几千到几百万用户交互的大规模应用程序时,你必须选择 react/vue 以保持良好的用户体验并保持服务器的健康!
    猜你喜欢
    • 1970-01-01
    • 2020-01-25
    • 2022-11-17
    • 2014-11-15
    • 2018-03-22
    • 2021-08-21
    • 2022-01-16
    • 2020-02-21
    • 1970-01-01
    相关资源
    最近更新 更多