intrfce / laravel-inertia-components
v0.1.1
2024-08-31 00:00 UTC
Requires
- php: ^8.2.0
- inertiajs/inertia-laravel: ^1.3
- laravel/framework: ^11.0.0
Requires (Dev)
- orchestra/testbench: ^9.4
- pestphp/pest: ^2.23
- pestphp/pest-plugin-laravel: ^2.4
- tightenco/duster: ^3.0
README
警告
此软件包处于预发布状态,API 可能会更改。
此软件包允许您为您的 InertiaJS 应用程序创建类似 Livewire 风格的类组件。
功能
- ✅ 在同一类中定义 HTTP 命名资源风格方法
show/store/update/destroy。 - ✅ 任何
public属性或方法都将数据传递回组件。 - ✅ 属性标记公共方法为
#[Lazy]或#[Always] - ✅ 使用
#[PostAction]、#[GetAction]等属性创建自动绑定自身路由的方法。 - ⌛ 使用
php artisan make:inertia创建组件 - ✅
Route::inertia辅助函数。
为什么?
- 更好的代码组织和封装。
- 减少路由文件中的混乱。
HTTP/资源方法。
基类保留四个 public 方法名称以供使用,以及它们对应的 HTTP 方法
这些方法的行为就像控制器方法一样,因此您可以根据需要注入路由参数和依赖项。
public function show(Request $request, string $id, ModelName $model): array {}
从 show() 返回数据
当您的路由被 GET 请求击中时使用 show 方法。
如果您从该方法返回一个 array,它将与其余的公共属性和方法合并,您也可以在这里使用常规的 Inertia::lazy 和 Inertia::always 闭包。
自动绑定 HTTP 方法。
如果您需要调用另一个非 RESTful 或与您显示的资源无关的路由,您可以使用自动绑定方法,这些方法将为您注册路由,使用自动或用户指定的 URL。
例如,在您的 show 路由上显示博客文章列表,但想要发送快速 AJAX 请求来切换文章的发布状态或取消发布状态?
在组件中设置一个函数,并向它添加适当的 HTTP 方法动作属性
#[PatchAction(url:'/{post}/toggle-published')] function togglePublished(BlogPost $post) { $post->published = !$post->published; $post->save(); return redirect()->back(); }
假设您的组件已注册为路径 /posts,这将自动为您注册一个路由 POST posts/{post}/toggle-published。
注意:如果您使用
#[GetAction]属性,则不应从其中返回 Inertia::response() - 如果您想这样做,请使用另一个完全注册的路由。
完整(WIP)示例
<?php class Dashboard extends Intrfce\InertiaComponents\InertiaComponent { // A template is required, or an exception will be thrown. protected $template = 'Dashboard/Index'; // Any public properties are passed to inertia. public string $name = 'Dan'; // As are any public methods. public function email(): string { return 'dan@hello.com'; } // You can mark any method as Inertia::lazy() with the #[Lazy] Attribute: #[Lazy] public function blogPosts(): Collection { return BlogPosts::all(); } // You can mark any method as Inertia::always() with the #[Always] Attribute: #[Always] public function age(): int { return 36; } /** GET /dashboard */ public function show(Request $request) {} /** POST /dashboard */ public function store(Request $request) {} /** PUT/PATCH /dashboard */ public function update(Request $request) {} /** DELETE /dashboard */ public function destroy(Request $request) {} /** GET /dashboard/your-route - Autowired */ #[GetAction('your-route')] public function getMoreStuff() { } /** POST /dashboard/your-route - Autowired */ #[GetAction('your-route')] public function postMoreStuff() { } /** PATCH /dashboard/patch-more-stuff - Autowired - notice the route URL derived from the function name */ #[PatchAction()] public function patchMoreStuff() { } /** DELETE /dashboard/{item}/delete - Autowired */ #[DeleteAction('{item}/delete')] public function deleteAnItem(ItemModel $item) { } }