stephancasas / blade-wants-attributes
为 Laravel Blade 类组件提供所有属性(包括不规则模式)。
Requires
- php: ^7.4|^8.0
- illuminate/support: ^8.0|^9.0
Requires (Dev)
- orchestra/testbench: ^7.7
- phpunit/phpunit: ^9.0
This package is auto-updated.
Last update: 2024-09-30 01:41:11 UTC
README
blade-wants-attributes
允许你在 Laravel Blade 类组件的构造函数中使用 Blade/HTML 定义的属性。
为什么?
Blade 类组件有很多优点,但开发者在类签名中使用它们时,需要将属性声明为构造函数的参数。由于这个要求,包含非标准字符(例如 wire:model
、wire:model.defer
等)的属性完全无法访问类构造函数或由类构造函数调用的方法。
blade-wants-attributes
注册了一个 Blade 预编译器,在组件实例初始化之前将属性提供给 ViewServiceProvider
。然后,通过将 WantsAttributes
特性添加到类签名并在构造函数中调用 $this->wantsAttributes()
,属性就可以通过组件构造函数访问。
好吧,但为什么?
如果你正在编写一个组件包,将复杂的组件逻辑提取到类方法中可能很有用。例如,你可能有时需要动态或条件性地渲染 Livewire 或 AlpineJS 的标记。为此,你需要访问不可用于 Blade 类组件的非标准 HTML 属性。
安装
您可以通过 composer 安装此包
composer require stephancasas/blade-wants-attributes
用法
将 StephanCasas\BladeWantsAttributes\Traits\WantsAttributes
特性应用到您的类组件中,并调用 $this->wantsAttributes()
。
namespace App\View\Components; use Illuminate\View\Component; class Select extends Component { use StephanCasas\BladeWantsAttributes\Traits\WantsAttributes; public $wireModel; public function __construct() { $this->wantsAttributes(); $this->wireModel = $this->attributes ->get('wire:model'); } //... public function render() { return view('components.select'); } }
或者,如果您不想将属性包应用到组件的 $attributes
属性上,您也可以通过 $this->getAllAttributes()
方法访问提供的属性
namespace App\View\Components; use Illuminate\View\Component; class Select extends Component { use StephanCasas\BladeWantsAttributes\Traits\WantsAttributes; public $isLivewire; public function __construct() { $this->isLivewire = $this->getAllAttributes() ->has('wire:model'); } //... public function render() { return view('components.select'); } }
许可证
MIT — 更多信息请参阅 许可证文件。