1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravel/Vue3/Inertia.js 部分的なリロードについて

Posted at

Inertia.jsについて

apiレスで、クライアント/サーバー間のデータの受け渡しができるinertia.jsですが、最近出たライブラリということもあってソースが少ないので少しまとめました。

部分的リロード

ページごと返すというのがデフォルト使用のinertiaですが、データを選択して、部分的に更新することも可能です。
inertiaのonlyメソッドを使いましょう。

Controller

渡したいパラメーターを分離します。

DashboardController.php
<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
class DashboardController extends Controller
{

    public function __construct(Request $request){
        Log::debug("Constructor passed");
    }
    public function __invoke(Request $request){
        return Inertia::render('Mashboard', [
            'data' => $posts,
            'static_num' =>random_int(1, 10000), //ランダムな数を返す。
            'dynamic_num' =>random_int(1, 10000), //1から10000までの間
       ]);
    }
}

View

:onlyを使って、更新したいデータを配列形式で渡します。

dashboard.vue
<script setup>
import { Link } from '@inertiajs/vue3';
defineProps({
    static_num:Number,
    dynamic_num:Number, //こいつだけを更新したい。
});

</script>
<template>

    <div class="text-[30px] flex flex-col justify-center items-center py-[100px]">
        <h2> Pertial reload test </h2>
        <p>動的な値:{{dynamic_num}}</p>
        <p>静的な値:{{static_num}}</p>
        <div class="text-center w-[680px] my-5">
            <Link href="/mashboard" :only="['dynamic_num']"> 
                <div class="border border-blue-300 my-3 bg-blue-200 rounded-full py-2 px-3">
                    <button>更新</button>
                </div>
            </Link>
          </div>
    </div>
</template>

結果

onlyで指定した変数だけ更新することができました。

ちなみに、更新のたびにControllerを通過しているのはLogによる裏付けで確認できます。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?