wire:replace
LivewireのDOM diffing は、ページ上の既存の要素を更新するのに役立ちますが、要素の内部状態をリセットするために、一部の要素を最初からレンダリングし直す必要がある場合があります。Livewire's DOM diffing is useful for updating existing elements on your page, but occasionally you may need to force some elements to render from scratch to reset internal state.
このような場合、wire:replace
ディレクティブを使用すると、Livewireに要素の子要素のDOM diffing をスキップし、代わりにコンテンツをサーバからの新しい要素で完全に置き換えるように指示できます。In these cases, you can use the wire:replace
directive to instruct Livewire to skip DOM diffing on the children of an element, and instead completely replace the content with the new elements from the server.
これは、サードパーティのJavaScriptライブラリやカスタムWebコンポーネントを扱う場合、または要素の再利用が状態を維持する際に問題を引き起こす可能性がある場合に最も役立ちます。This is most useful in the context of working with third-party javascript libraries and custom web components, or when element re-use could cause problems when keeping state.
以下は、shadow DOMを持つWebコンポーネントを wire:replace
でラップし、Livewireが要素を完全に置き換えることで、カスタム要素が自身のライフサイクルを処理できるようにする例です。Below is an example of wrapping a web component with a shadow DOM wire:replace
so that Livewire completely replaces the element allowing the custom element to handle its own life-cycle:
<form>
<!-- ... -->
<div wire:replace>
<!-- This custom element would have its own internal state -->
<json-viewer>@json($someProperty)</json-viewer>
</div>
<!-- ... -->
</form>
wire:replace.self
を使用すると、ターゲット要素とすべての子要素を置き換えるようにLivewireに指示することもできます。You can also instruct Livewire to replace the target element as well as all children with wire:replace.self
.
<div x-data="{open: false}" wire:replace.self>
<!-- Ensure that the "open" state is reset to false on each render -->
</div>