LoginSignup
0
0

inertiajsによるリンク、form submit、APIリクエストの実装

Posted at

画面遷移のリンクの場合

Linkを使う。
※aタグを直接使うとSPAによる部分リロードのメリットがなくなる。

通常はaタグにレンダリングされる。

import { Link } from '@inertiajs/vue3';

<Link href="/About">About</Link>

formのsubmitによる画面遷移

inertiajsのrouterかそのヘルパーであるformヘルパー(useForm)を使う
useFormの場合はデータのエラー時や、初期値のバインドも簡単にできる。

<script setup>
import { useForm } from '@inertiajs/vue3';

const props = defineProps({
  user: Oject,
});

const form = useForm({
  id: props.user.id,
  name: props.user.name,
  age: props.user.age,
});

const submit = (event) => {
  form.post('/register'); 
  // ziggyを導入している場合、以下のようにもできる
  form.post(route('register'));
}

</script>
<template>
  <form @submit.prevent="submit">
    <input type="text" v-model="form.name"/>
    <div v-if="form.errors.name">{{ form.errors.name }}</div>
    ...
  </form>
</template>
Controller
  public function register(Request $request)
  {
      $request->validate([
        'name' => ['required', 'max:10'],
        'age' => ['required', 'integer'],
      ]);
      $user = new User([
        'name' => $request->name,
        'age' => $request->age,
      ]);
      return Inertia::render('Login');
  }

laravel側のバリデーションエラー時、form.errorsにエラー内容が格納される。

useFormはformタグありきっぽい実装なため
formタグを置きにくいタグ構成やsubmitボタンがネストしてしまうなどの場合あuseFormのマニュアル版であるrouterを使う。

こちらもinertiajsの機能なので画面遷移する想定の応答にする必要がある。

画面遷移のないAPIリクエストの場合

router/useFormでAPIを実行するとinertia固有のjson形式でないためエラーとなる。
APIを実行する場合はaxios、XHR、fetchなどのHTTPリクエストを使う。

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