Skip to content
全部文档

wire:show

Livewire 的 wire:show 指令可根据表达式结果轻松显示或隐藏元素。

wire:show 与在 Blade 中使用 @if 不同:它用 CSS(display: none)切换可见性,而不是把元素从 DOM 中完全移除。元素仍留在页面中只是被隐藏,因此可以更流畅地过渡,且无需与服务器往返。

基本用法

下面是一个实用示例,用 wire:show 切换「Create Post」模态框:

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>

点击「Create New Post」按钮时,模态框会在无需服务器往返的情况下出现。成功保存文章后,模态框会隐藏并重置表单。

使用过渡

你可以把 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 过渡类会在模态框显示与隐藏时产生淡入淡出与缩放效果。

View the full x-transition documentation →

参考

blade
wire:show="expression"

该指令没有修饰符。