titonova/x-livewire

一个允许您像使用blade组件一样使用livewire组件的包。即,给它slot、属性等。

1.2.0 2023-10-12 12:11 UTC

This package is auto-updated.

Last update: 2024-09-12 14:09:39 UTC


README

⚠️ 目前处于beta阶段。请勿在生产环境中使用(未经测试)。欢迎贡献

X-livewire

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

此包允许您像blade组件一样渲染livewire组件,给它属性、slot等。

假设您想要创建一个名为alert的livewire组件,通常您会通过:<livewire:alert/>来渲染组件。然而,有几个问题。

  1. 您不能在组件中允许slot。也就是说,这是无效的:<livewire:alert>Alert</livewire:alert>
  2. 您无法访问$attributes包。因此,无法直接访问$attributes变量。也就是说,如果您这样做:<livewire:alert title="Alert!">,您无法通过$attributes->get('title')访问$title属性。相反,您必须将$title作为一个公开属性放在组件中。更不用说,$attributes上的其他方法也不可用。例如,->merge([])->whereStartsWith()等。

livewire的创建者Caleb Porzio已经明确表示,添加slot、属性等目前不在roadmap中

这就是我创建X-livewire的原因。

使用X-Livewire,您可以这样做

    <x-livewire _="alert">
        My alert message
    </x-livewire>

而且,就像Blade一样,您可以

  1. 访问$attributes变量:{{ $attributes->get('title') }},
  2. 访问$slot变量:{{ $slot }}

安装

您可以通过composer安装此包

composer require titonova/x-livewire

用法

  1. 在创建您的livewire组件后,让它扩展XLivewireBaseComponent而不是Component。例如:class Alert extends XLivewireBaseComponent{
  2. 如果您想在x-livewire组件的后端访问$attributes包,在组件的mount()方法的第一行添加$this->setProps()
  3. 在组件的视图文件中,例如alert.blade.php,在文件顶部添加@setUpXLivewire
  4. 当您想要渲染组件时:Blade <x-livewire _="alert" title="Warning"> My alert message </x-livewire>

您可以使用和Blade组件中一样的方式访问$slot$attributes变量:{{ $slot }} {{ $attributes->get('title') }}

您还可以访问传递给x-livewire组件标签的属性数组,但这些属性在类中没有显式声明为$tagAttributes属性。例如,{{ $tagAttributes->get('href') }}。例如,像primarylg等不需要在类中有对应的属性声明。例如 ```HTML Google ....

    <span>
    <a href="{{ $tagAttributes->get('href') }}>{{ $slot }}</a>
    </span>
```

您可以如此添加并访问命名slot

            My alert message
            <x-slot name="footer">My custom footer </x-slot>
        </x-livewire>
        
        ....

        <div class="alert ...">
            {{ $slot }}
            <div class="alert-footer">
                {{ $footer ?? 'Default footer content' }}
            </div>
        </div>

如果您想直接以它们的Illuminate\View\ComponentSlot类访问slot,可以使用以下方法:$this->laravelSlots()['footer']。这将返回一个Illuminate\View\ComponentSlot的实例。例如

    +attributes: Illuminate\View\ComponentAttributeBag {#1379 ▼
      #attributes: []
    }
    #contents: "<b>&lt;i&gt;hello!!!    &lt;/i&gt; </b>"

有以下可用方法

public withAttributes(array $attributes): $this Set the extra attributes that the slot should make available.
public toHtml(): string Get the slot's HTML string.
public isEmpty(): bool Determine if the slot is empty.
public isNotEmpty(): bool Determine if the slot is not empty.
public __toString(): string Get the slot's HTML string.

测试

composer test

更新日志

请参阅更新日志以获取有关最近更改的更多信息。

待办事项/路线图

[ ] 添加测试

[ ] 缩短标签声明为<x-livewire:alert>

贡献

请参阅贡献以获取详细信息。

安全漏洞

请审查我们的安全策略,了解如何报告安全漏洞。

鸣谢

许可协议

MIT 许可协议 (MIT)。请参阅许可文件获取更多信息。