Skip to content

wire:show

Livewire 的 wire:show 指令使根据表达式的结果显示和隐藏元素变得容易。

wire:show 指令与在 Blade 中使用 @if 不同,它使用 CSS(display: none)切换元素的可见性,而不是完全从 DOM 中删除元素。这意味着元素保留在页面中但被隐藏,允许更平滑的过渡而无需服务器往返。

基本用法

以下是使用 wire:show 切换"创建文章"模态框的实际示例:

php
use Livewire\Component;
use App\Models\Post;

class CreatePost extends Component
{
    public $showModal = false;

    public $content = '';

    public function save()
    {
        Post::create(['content' => $this->content]);

        $this->reset('content');

        $this->showModal = false;
    }
}
blade
<div>
    <button x-on:click="$wire.showModal = true">New Post</button>

    <div wire:show="showModal">
        <form wire:submit="save">
            <textarea wire:model="content"></textarea>

            <button type="submit">Save Post</button>
        </form>
    </div>
</div>

当单击"创建新文章"按钮时,模态框出现而无需服务器往返。成功保存文章后,模态框被隐藏,表单被重置。

使用过渡

你可以将 wire:show 与 Alpine.js 过渡结合起来创建平滑的显示/隐藏动画。由于 wire:show 仅切换 CSS display 属性,Alpine 的 x-transition 指令与之完美配合:

blade
<div>
    <button x-on:click="$wire.showModal = true">New Post</button>

    <div wire:show="showModal" x-transition.duration.500ms>
        <form wire:submit="save">
            <textarea wire:model="content"></textarea>
            <button type="submit">Save Post</button>
        </form>
    </div>
</div>

上面的 Alpine.js 过渡类将在模态框显示和隐藏时创建淡入淡出和缩放效果。

查看完整的 x-transition 文档 →