LoginSignup
8
3

More than 1 year has passed since last update.

Inertiaとは

Last updated at Posted at 2023-02-14

laravelとvue.jsを使用してプロジェクトを作成した際に、使用していて便利だなと感じた
Inertiaについて振り返りも含めたメモとしてInertiaについて記載しています。

Inertiaとは

Inertiaとは簡単に、サーバーサイド(バックエンド)とクライアントサイド(フロントエンド)をつなぐためのツールです。
今回でいうとクライアントサイド(Vue.js)とサーバーサイド(Laravel)に当たります。
公式でも下記のように記載しているように接着剤みたいなものだと考えるとわかりやすいです。

Inertiaはフレームワークではありませんし、既存のサーバサイドやクライアントサイドのフレームワークと置き換わるものでもありません。むしろ、それらと一緒に動作するように設計されています。Inertiaは両者をつなぐ接着剤のようなものだと考えてください。

ちなみにInertiaの読み方は「イナーシャ」というみたいです。
思いっきりイナーティアって読んでいました、、

Inertiaが対応しているもの

クライアントサイド
React
Vue
Svelte

サーバーサイド
Laravel
Rails

Inertia使用するメリット

これまでのLaravelと同じ感覚でVueやReactなどのモダンフロントを使用することができる

Laravelでは、コントローラーで処理を行い、これをビュー側(blade.php)に受け渡してページを表示したりします。
Vue.jsを使う場合にも、基本的には、同じような手順で処理を行えます。ただ、Webアプリ全体で使える ルート設定が使えなかったりと色々な不便があります。
Inertiaを使えば、Vue側でも、laravelのルート設定を使ったり、ヘッダを組み込んだり、ページネーションを簡単に搭載したりできます。

Inertia使用した実装

ルーティング

routes/web.php
Route::resource('items', ItemController::class)
    ->middleware(['auth', 'verified']);

コントローラー

App\Http\Controllers\ItemController.php
<?php
namespace App\Http\Controllers;

use App\Http\Requests\StoreItemRequest;
use App\Http\Requests\UpdateItemRequest;
use App\Models\Item;
use Inertia\Inertia;

class ItemController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $items = Item::select('id', 'name', 'price', 'is_selling')->get();

        //Inertia::renderという関数は第一引数にコンポーネント、第二引数にプロパティ配列を渡します。
        //Inertia::renderを呼び出す事で、どのコンポーネントに対してどの変数をセットするかをここできめ、vueにも反映させることができます。
        return Inertia::render('Items/Index', [
            'items' => $items
        ]);
    }

ビュー側

resources/js/Pages/Items/index.vue
<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
import { Head, Link } from '@inertiajs/vue3';

defineProps({
    items: Array
})
</script>

<template>
~~省略〜〜
<tbody>
   <tr v-for="item in items" :key="item.id">
       <td class="px-4 py-3">{{ item.id }}</td>
       <td class="px-4 py-3">{{ item.name }}</td>
       <td class="px-4 py-3">{{ item.price }}</td>
       <td class="px-4 py-3">{{ item.is_selling }}</td>
   </tr>
</tbody>
~~省略〜〜
</template>
8
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3