php - Laravel Livewire : load livewire component with button click

标签 php laravel laravel-livewire livewires

有 3 个 livewire 组件 UserIsExpiredUserIsActiveUserIsPending 以及每个组件对应的 3 个按钮。单击按钮时,它应该用其各自的组件替换先前的组件。

<button wire:click="$emit(active)">{{ __('Active') }}</button>
<button wire:click="$emit(pending)">{{ __('Pending') }}</button>
<button wire:click="$emit(expired)">{{ __('Expired') }}</button>

在 View 中

<livewire:user-is-active :active="$active"/>
<livewire:user-is-pending :pending="$pending"/>
<livewire:user-is-expired :expired="$expired"/>

组件示例

class UserIsExpired extends Component
{
    protected $listeners = ['expired'];    
    public function render()
    {
        return <<<'blade'
            <div>
                {{-- The best athlete wants his opponent at his best. --}}
            </div>
        blade;
    }
}

当点击Active 按钮时,它应该加载UserIsActive 组件。其他两个也一样。

我一直在寻找 livewire 文档,但无法找到实现它的方法。提前致谢。

最佳答案

我会将您的组件包装在一个组件容器中,并使用它来管理您其他组件的可见性。

component-contaoner.blade.php

<div>
    <h4>Component Container</h4>

    {{-- this is your dynamic component --}}
    @livewire($component, key($key))

    <button wire:click="$emit('switch', 'active')">
        {{ __('Active') }}
    </button>

    <button wire:click="$emit('switch', 'pending')">
        {{ __('Pending') }}
    </button>

    <button wire:click="$emit('switch', 'expired')">
        {{ __('Expired') }}
    </button>
</div>

ComponentContainer.php

class ComponentContainer extends Component
{
    private $component = '';

    protected $listeners = [
        'switch'
    ];

    public function switch(string $component)
    {
        $this->component = $component;
    }

    public function mount(string $component = 'active')
    {
        $this->component = $component;
    }

    public function render()
    {
        return view('livewire.component-container', [
            'component' => $this->component,
            // key is required to force a refresh of the container component
            'key' => random_int(-999, 999),
        ]);
    }
}

然后您将按如下方式使用组件容器,传入一个可选的组件以显示初始值,否则它默认为active,如在mount 函数。

@livewire('component-container')

您可以将按钮放在任何您想要使用的地方

$emitTo('container-component', 'switch', 'active')

为了方便起见,我只是将它们放在 component-container 中。

这种方法的一个好处是没有要管理的 if 条件,如果您添加更多 components 来在它们之间切换,您需要做的就是添加另一个 button 某处有相关的 $emit

关于php - Laravel Livewire : load livewire component with button click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67817181/

相关文章:

php - 未找到 InvalidArgumentException View [layouts.app]。 Laravel-8 LiveWire-2

php - 创建订单时将 WooCommerce 订单状态从处理中设置为待处理

laravel - 如何在 Eloquent 中使用 join 和 sum?

php - Laravel 调用未定义的方法 Illuminate\Html\HtmlServiceProvider::style()`

mysql - 如何在 Laravel 5.5 中的每个新连接上设置 mysql 用户变量?

laravel-routing - 在 Livewire 中如何通过名称使用路由?

php - 在mysql数据库中插入数组的所有可能方法有哪些

PHP在另一台服务器上执行PHP并得到结果

php - SQL查询——如何从数组中获取值?

Laravel Livewire key() 期望参数 1 为数组,给定整数 |嵌套组件 |在循环中加载组件