【Laravel實戰】5分鐘搞懂Livewire組件的查詢字串
有時候在組件狀態改變時去更新瀏覽器的查詢字串是有必要的
例如你打造一個 "search posts" 組件,並且希望查詢字串能夠反應出當前的查詢內容為何,像下面這個例子
https://your-app.com/search-posts?search=some-search-string
這樣的話,當使用者點下返回鍵或者是將頁面加入最愛,就能夠透過查詢字串來回到當前狀態,而不需要每次都要重新設定組件的狀態
為了達到這樣的目的,你能夠加入 protected $queryString 這樣的屬性,這樣的話 Livewire 將會隨著每次屬性的改動進而修改查詢字串,反過來說當查詢字串改變時也會改動這個屬性的值
//app/Http/Livewire/SearchPosts.php
class SearchPosts extends Component
{
public $search;
protected $queryString = ['search'];
public function render()
{
return view('livewire.search-posts', [
'posts' => Post::where('title', 'like', '%'.$this->search.'%')->get(),
]);
}
}
//resources/views/livewire/search-posts.blade.php
<div>
<input wire:model="search" type="search" placeholder="Search posts by title...">
<h1>Search Results:</h1>
<ul>
@foreach($posts as $post)
<li>{{ $post->title }}</li>
@endforeach
</ul>
</div>
保持乾淨的查詢字串
根據上面的例子,當 search 屬性是空的時,查詢字串看起來像這樣:
?search=
這樣看起來有點不夠好,或許你希望只有在它不是預設設定時才出現查詢字串的值。例如假如你有一個 $page 屬性用來追蹤組件的分頁數,你可能會希望當頁面為首頁時從查詢字串上拿掉 page 屬性,這時你可以使用以下的語法:
class SearchPosts extends Component
{
public $foo;
public $search = '';
public $page = 1;
protected $queryString = [
'foo',
'search' => ['except' => ''],
'page' => ['except' => 1],
];
public function mount()
{
$this->fill(request()->only('search', 'page'));
}
...
}



