ambengers / kinetic
为 Inertia.js Laravel 适配器添加类似视图编写的功能。
1.9
2024-06-05 02:01 UTC
Requires
- php: ~8.0.0|~8.1.0|~8.2.0|^8.3
- inertiajs/inertia-laravel: ~0.5|~0.6|^1.0
Requires (Dev)
- nunomaduro/larastan: ^2.0
- orchestra/testbench: ^4.0|^5.0|^6.4|^7.0
- phpunit/phpunit: ^8.0|^9.5.8
README
一个向 Inertia.js Laravel 适配器添加类似视图编写功能的包。
用于根据 Inertia 组件名称共享属性。
安装
$ composer require ambengers/kinetic
使用方法
如果您已经熟悉 Laravel 中的视图编写器如何工作,这将非常直观。
基本注册
您可以在任何服务提供程序中使用 Inertia::composer()
注册特定组件的编写器。第一个参数接受字符串或 Inertia 组件的数组,第二个参数接受类字符串或闭包。
use Inertia; use Inertia\ResponseFactory; use App\Composers\UserComposer; class AppServiceProvider extends ServiceProvider { public function boot() { // Class-based Composer.. Inertia::composer('User/Profile', UserComposer::class); // Closure-based Composer.. Inertia::composer('User/Profile', function (ResponseFactory $inertia) { // }); } }
通配符注册
您还可以使用通配符 *
语法注册多个组件或全局的编写器。
// Components within User directory will receive data from UserComposer class Inertia::composer('User/*', UserComposer::class); // All components will receive data from GlobalComposer class Inertia::composer('*', GlobalComposer::class);
基于类的编写器
您可以使用以下命令生成您的编写器类
$ php artisan kinetic:composer UserComposer
然后您可以在 compose 方法中调用 $inertia->with()
方法来设置编写的属性,如下所示
class UserComposer { public function compose(ResponseFactory $inertia) { $inertia->with('list', ['foo' => 'bar', 'baz' => 'buzz']); } }
基于闭包的编写器
如果您选择基于闭包的编写器,您的闭包必须接受 Inertia\ResponseFactory
类的实例作为第一个参数。然后您可以从工厂类调用 with()
方法来设置编写的属性,如下所示
Inertia::composer('User/Profile', function (ResponseFactory $inertia) { $inertia->with([ 'post' => [ 'subject' => 'Hello World!', 'description' => 'This is a description.' ] ]); });
多个编写器
您还可以使用数组为组件设置多个编写器,如下所示
Inertia::composer(['User/Profile', 'User/Index'], [ UserComposer::class, function (ResponseFactory $inertia) { $inertia->with(...); } ]);
该数组将自动与组件的任何现有编写器合并。
当您调用 Inertia::render('User/Profile')
时,属性现在应包括编写的数据。
安全
如果您发现任何与安全相关的问题,请通过电子邮件发送给作者,而不是使用问题跟踪器。
许可
有关更多信息,请参阅许可文件。