titonova/ x-livewire
一个允许您像使用blade组件一样使用livewire组件的包。即,给它slot、属性等。
Requires
- php: ^8.1
- illuminate/contracts: ^9.0 || ^10.0
- livewire/livewire: ^3.0
- spatie/laravel-package-tools: ^1.9.2
Requires (Dev)
- jeroen-g/laravel-packager: ^2.8
- laravel/pint: ^1.0
- nunomaduro/collision: ^6.0
- orchestra/testbench: ^7.0
- pestphp/pest: ^1.21
- pestphp/pest-plugin-laravel: ^1.1
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-12 14:09:39 UTC
README
⚠️ 目前处于beta阶段。请勿在生产环境中使用(未经测试)。欢迎贡献
X-livewire
此包允许您像blade组件一样渲染livewire组件,给它属性、slot等。
假设您想要创建一个名为alert
的livewire组件,通常您会通过:<livewire:alert/>
来渲染组件。然而,有几个问题。
- 您不能在组件中允许slot。也就是说,这是无效的:
<livewire:alert>Alert</livewire:alert>
。 - 您无法访问
$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一样,您可以
- 访问
$attributes
变量:{{ $attributes->get('title') }}
, - 访问
$slot
变量:{{ $slot }}
安装
您可以通过composer安装此包
composer require titonova/x-livewire
用法
- 在创建您的livewire组件后,让它扩展
XLivewireBaseComponent
而不是Component
。例如:class Alert extends XLivewireBaseComponent{
- 如果您想在x-livewire组件的后端访问
$attributes
包,在组件的mount()
方法的第一行添加$this->setProps()
。 - 在组件的视图文件中,例如
alert.blade.php
,在文件顶部添加@setUpXLivewire
。 - 当您想要渲染组件时:
Blade <x-livewire _="alert" title="Warning"> My alert message </x-livewire>
您可以使用和Blade组件中一样的方式访问$slot
和$attributes
变量:{{ $slot }} {{ $attributes->get('title') }}
您还可以访问传递给x-livewire组件标签的属性数组,但这些属性在类中没有显式声明为$tagAttributes
属性。例如,{{ $tagAttributes->get('href') }}
。例如,像primary
、lg
等不需要在类中有对应的属性声明。例如 ```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><i>hello!!! </i> </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)。请参阅许可文件获取更多信息。