🐡
Inertiaを使用してコントローラからビューに値を渡すときのお作法(vue.js&Laravel)
●コントローラの書き方
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Models\InertiaTest;
class InertiaTestController extends Controller
{
public function index()
{
return Inertia::render('Inertia/Index', ['blogs' => InertiaTest::all()]);
}
POINT
・Inertia::render メソッドを使用して、ビュー(フロントエンドコンポーネント)とデータを結びつける。
違い↓
Laravel Blade
view('viewファイル名', compact(変数名))
Inertia
Inertia::render('コンポーネント名', [変数名])
・フロントエンドのコンポーネントとLaravelのコントローラで統一した命名規則を使用する。
●ビューに渡す
<template>
<div class="p-4">
<h1 class="text-2xl font-bold mb-4">ブログ一覧</h1>
<ul>
<li
v-for="blog in blogs"
:key="blog.id"
class="mb-2 p-2 border rounded shadow"
>
<h2 class="text-xl font-semibold">{{ props.blog.title }}</h2>
<p class="text-gray-700">{{ props.blog.content }}</p>
</li>
</ul>
</div>
</template>
<script setup>
const props = defineProps({
blogs: Array,
})
</script>
POINT
・definePropsの関数を使用しコントローラから値を受け取る。
・<template>タグ内ではpropsをつける
Discussion