主题
@teleport
@teleport 指令用于将模板的一部分渲染到 DOM 中的其他位置,脱离组件的正常放置位置。
基本用法
用 @teleport 包裹内容,并使用 CSS 选择器指定渲染位置:
blade
<div>
<div x-data="{ open: false }">
<button @click="open = ! open">切换模态框</button>
@teleport('body')
<div x-show="open">
模态框内容...
</div>
@endteleport
</div>
</div>模态框内容将被渲染到 <body> 元素的末尾:
html
<body>
<!-- 页面内容... -->
<div x-show="open">
模态框内容...
</div>
</body>任何有效的 CSS 选择器
@teleport 选择器可以是任何你传递给 document.querySelector() 的字符串,例如 'body'、'#modal-root' 或 '.modal-container'。
为什么使用 Teleport?
Teleporting 对于嵌套的模态框、下拉菜单和弹出框非常有用,因为父元素的样式或 z-index 值可能会干扰正确的渲染。
不使用 teleporting:
blade
<div style="z-index: 10;">
<!-- z-index 为 10 的父模态框 -->
<div style="z-index: 20;">
<!-- 子模态框继承父元素的层叠上下文 -->
<!-- 背景遮罩可能无法正确覆盖父模态框 -->
</div>
</div>使用 teleporting:
blade
<div style="z-index: 10;">
<!-- 父模态框 -->
@teleport('body')
<div style="z-index: 20;">
<!-- 子模态框在 body 层级作为兄弟元素渲染 -->
<!-- 背景遮罩可以正确覆盖所有内容 -->
</div>
@endteleport
</div>常见用例
模态对话框:
blade
@teleport('body')
<div class="fixed inset-0 bg-black/50" x-show="showModal">
<div class="modal">
<!-- 模态框内容... -->
</div>
</div>
@endteleport下拉菜单:
blade
@teleport('body')
<div class="absolute" x-show="open" style="top: {{ $top }}px; left: {{ $left }}px;">
<!-- 下拉菜单项... -->
</div>
@endteleportToast 通知:
blade
@teleport('#notifications-container')
<div class="toast">
{{ $message }}
</div>
@endteleport重要约束
必须 teleport 到组件外部
Livewire 仅支持将 HTML teleport 到组件外部。Teleport 到同一组件内的其他元素将不起作用。
需要单个根元素
@teleport 语句内只能包含一个根元素。不支持多个根元素。
有效:
blade
@teleport('body')
<div>
<h2>标题</h2>
<p>内容</p>
</div>
@endteleport无效:
blade
@teleport('body')
<h2>标题</h2>
<p>内容</p>
@endteleport由 Alpine 驱动
此功能底层使用 Alpine 的 x-teleport 指令。
参考
blade
@teleport(string $selector)
<!-- 内容 -->
@endteleport| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
$selector | string | 必需 | 指定内容渲染位置的 CSS 选择器(如 'body'、'#modal-root'、'.container') |