【Laravel實戰】15分鐘搞懂Livewire的生命週期Hook
每個 Livewire 組件都服從一個相同的生命週期,而生命週期函式允許你在組件的各個階段去執行程式碼,又或者是在屬性被更新之前
class HelloWorld extends Component
{
public $foo;
public function mount()
{
//只會執行一次,就在組件被初始化的那一刻,會在 render() 呼叫前
}
public function hydrate()
{
//在每一個請求時呼叫,就在組件被 hydrated 之後,但會在 action 執行或 render() 呼叫前
}
public function hydrateFoo($value)
{
//在名為 $foo 的屬性被 hydrated 之前被呼叫
}
public function dehydrate()
{
//在每一個請求時呼叫,就在組件被 dehydrated 之前,但會在 render() 呼叫之後
}
public function dehydrateFoo($value)
{
//在名為 $foo 的屬性被 dehydrated 之前被呼叫
}
public function updating($value, $name)
{
//在任何組件上的資料被更新前被呼叫,比如使用 wire:model,而不是直接在PHP程式碼內
}
public function updated($value, $name)
{
//在任何組件上的資料被更新後被呼叫,比如使用 wire:model,而不是直接在PHP程式碼內
}
public function updatingFoo($value)
{
//在組件上的$foo屬性更新前被呼叫
}
public function updatedFoo($value)
{
//在組件上的$foo屬性更新後被呼叫
}
public function updatingFooBar($value)
{
//在組件上的$foo巢狀屬性更新前被呼叫
}
public function updatedFooBar($value)
{
//在組件上的$foo巢狀屬性更新後被呼叫
}
}
Javascript Hooks
Livewire 給你一個在某些事件下去執行 JS 程式的機會
| Hooks | 描述 |
|---|---|
| component.initialized | 當頁面上的組件被 Livewire 初始化時會被呼叫 |
| element.initialized | 當 Livewire 初始化一個單獨的元素時被呼叫 |
| element.updating | 當 Livewire 更新一個元素前被呼叫 |
| element.updated | 當 Livewire 更新一個元素後被呼叫 |
| element.removed | 當 Livewire 移除一個元素後被呼叫 |
| message.sent | 當 Livewire 發出一個更新訊息到伺服器時被呼叫 |
| message.failed | 當訊息發送因不明原因失敗時被呼叫 |
| message.received | 當一個訊息已經完成旅程,即將在更新DOM樹前呼叫 |
| message.processed | 當 Livewire 完成發送訊息後所有的旅程作業,包含更新DOM樹之後呼叫 |
那該怎麼去使用勒?請看下面這段程式碼
<script>
document.addEventListener("DOMContentLoaded", () => {
Livewire.hook('component.initialized', (component) => {})
Livewire.hook('element.initialized', (el, component) => {})
Livewire.hook('element.updating', (fromEl, toEl, component) => {})
Livewire.hook('element.updated', (el, component) => {})
Livewire.hook('element.removed', (el, component) => {})
Livewire.hook('message.sent', (message, component) => {})
Livewire.hook('message.failed', (message, component) => {})
Livewire.hook('message.received', (message, component) => {})
Livewire.hook('message.processed', (message, component) => {})
});
</script>
總的來說,不管是在 PHP 端又或者是 JS 端,都有支援對應的 HOOKS ,請大家務必掌握起來喔!