在 Laravel Livewire 中将值从一页传递到另一页

Passing a value from one page to another in Laravel Livewire

我是 Livewire 的新手 Laravel,我有一个关于如何将值从一个页面传递到另一个页面的小问题。我有两个 livewire 组件和刀片(Booklist 和 Book)和一个 table 在 booklist 上呈现如下:

<table>
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Author</th>
        <th>Action</th>
    </tr>
    
    <tr>
        <td>1</td>
        <td>Harry Potter</td>
        <td>J.K. Rowling</td>
        <td><button>Details</button></td>
    </tr>
    
     <tr>
        <td>2</td>
        <td>Percy Jackson</td>
        <td>Rick Riordan</td>
        <td><button>Details</button></td>
    </tr>
    
     <tr>
        <td>3</td>
        <td>Game of Thrones</td>
        <td>George R.R. Martin</td>
        <td><button>Details</button></td>
    </tr>
</table>

场景是当用户点击“详情”按钮时,它会移动到另一个页面(图书)以显示该图书的全部详情。不幸的是,它至少无法传输那本书的 ID。我已经在 livewire 上尝试了 $emit 功能,但是它不起作用。

组件 1:

class Booklist extends Component
{
    public $data;
    public function render()
    {
        $this->data = Books::all();
        return view('livewire.bookstore.booklist');
    }

    public function getDetails($id){
        $this->emit('newPost', $id);
        return redirect()->to('bookstore/detail');
    }
}

组件 2:

class Book extends Component
{

    public $listeners = ['newPost'];
    public $numberid;
    public $data;

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

    public function newPost($id){
        $this->numberid = $id->id;
    }

    public function checkifdata(){
        session()->flash('message','Number is ' . $this->numberid);
    }
}

如果您打算为书籍详细信息设置不同的页面,那么您可以简单地按照 Full-Page Components 渲染。

Route::get('/booklist', Booklist::class);
Route::get('/book/{$book}', Books::class);

书目组成部分

class Booklist extends Component
{
    public $books;

    public function mount()
    {
        $this->books = Books::all();
    }

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

点击详情,会发生Route Model Binding

@foreach($books as $book)
    <td><a href="{{ url('book/' . $book->id) }}">Details</a></td>
@endforeach

图书组件

class Book extends Component
{

    public $book;

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

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