1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vue.jsでAPIを実行する手順(備忘録)

Last updated at Posted at 2024-10-29

はじめに

この記事は、Vue.jsを用いてLaravelのAPIを実行し、取得したレスポンス(データ)をブラウザに表示するアプリを実装した際の備忘録です。

内容に誤りや加筆が必要な場合、随時更新していきます。

プロジェクトを新規作成する

  • 参考リンク

Axiosのインストール

Vue.jsでAPI通信を行う場合は、Axiosが一般的によく使われています。

  • 参考リンク

Axiosのインストールは次のコマンドで実行できます

cd my-project
npm install axios

Vue.jsの準備

Laravelのサーバーからデータベースのデータを取得し、1レコードずつ表示させる

  • src/components
CustomerList.vue
<template>
  <div>
    <h1>顧客一覧</h1>
    <ul>
      <li v-for="customer in customers" :key="customer.id">
        {{ customer.name }} - {{ customer.email }}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      customers: []
    };
  },
  mounted() {
    this.fetchCustomers();
  },
  methods: {
    async fetchCustomers() {
      try {
        const response = await axios.get(`${process.env.VUE_APP_API_URL}/index`);

        this.customers = response.data;
      } catch (error) {
        console.error('APIエラー: ', error);
      }
    }
  }
};
</script>

<style scoped>

</style>

Vue.jsのコードに関する参考リンク

ルートの設定

  • src/router/index.js
index.js
import { createRouter, createWebHistory } from 'vue-router'

import CustomerList from '@/components/CustomerList.vue';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [

    {
      path: '/customers',
      name: 'CustomerList',
      component: CustomerList
    }
  ]
})

export default router

バックエンド側(Laravel)のコード

/indexにリクエストがあった場合、連携しているデータベースのデータを取得して、json形式でデータを返す(レスポンスする)

api.php
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CustomerController;



Route::get('/index', [CustomerController::class, 'index']);

<?php

namespace App\Http\Controllers;

use App\Models\Customer; // Customerモデルをインポート
use Illuminate\Http\Request;

class CustomerController extends Controller
{
    // 顧客情報を取得するメソッド
    public function index()
    {
        // 顧客情報を関連するモデルと一緒に取得
        $customers = Customer::with([
            'customer_contacts',
            'customer_favorite_products',
            'customer_notes',
            'customer_occupations',
            'customer_preferences',
            'customer_purchase_histories',
            'customer_reminders',
            'customer_social_media'
        ])->get(); // get()メソッドでデータを取得

        // JSON形式でレスポンスを返す
        return response()->json($customers);
    }
}

Laravelのメソッドに関する参考リンク

サーバーを起動するコマンド

Vue.jsの場合:npm run dev
Laravelの場合:php artisan serve

まとめ

各々のサーバーを起動しブラウザからVue.jsを開くことで、開かれたVue.jsからLaravelにリクエストが送信され、Laravelはデータを取得しVue.jsにデータをレスポンスします。データを受け取ったVue.jsはブラウザにデータを表示することができます

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?