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

【ToDoアプリ開発講座 第3回】Vueで画面を作成しAPIを呼び出す(フロントエンド)

Last updated at Posted at 2025-04-04

こんにちは!

前回は Spring BootでREST APIを作成 しました。 この第3回では、Vue 3を使って画面を作成し、APIを呼び出す手順を解説します!


今回の目標

  • Vite + Vue 3 のプロジェクト作成
  • 画面にタスク一覧を表示
  • 新規追加と削除の実装
  • Axios で Spring Boot API を呼び出す

1. Vue 3 + Vite のプロジェクト作成

npm create vite@latest todo-frontend -- --template vue
cd todo-frontend
npm install
npm install axios
npm run dev

2. コンポーネント構成

src/components/TodoApp.vue

<template>
  <div>
    <h1>ToDo App</h1>
    <input v-model="newTask" @keyup.enter="addTask" placeholder="新しいタスク" />
    <button @click="addTask">追加</button>
    <ul>
      <li v-for="task in tasks" :key="task.id">
        {{ task.title }}
        <button @click="deleteTask(task.id)">削除</button>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

const tasks = ref([])
const newTask = ref('')

const fetchTasks = async () => {
  const res = await axios.get('http://localhost:8080/api/tasks')
  tasks.value = res.data
}

const addTask = async () => {
  if (!newTask.value.trim()) return
  await axios.post('http://localhost:8080/api/tasks', { title: newTask.value })
  newTask.value = ''
  fetchTasks()
}

const deleteTask = async (id) => {
  await axios.delete(`http://localhost:8080/api/tasks/${id}`)
  fetchTasks()
}

onMounted(fetchTasks)
</script>

解説

このコンポーネントはタスクの表示・追加・削除という基本的なToDo機能を実装しています。

ref([])/ ref(''):Vue 3 の Composition API を使ってリアクティブな状態を定義しています。

onMounted(fetchTasks):初回マウント時に API からデータを取得して画面に表示。

fetchTasks():バックエンドの GET /api/tasks を呼び出して、全タスクを取得。

addTask():新しいタスクのタイトルを POST で送信し、登録後に一覧を更新。

deleteTask(id):指定IDのタスクを DELETE で削除し、再度一覧を取得。

v-model / v-for:Vueのテンプレート構文で、フォーム入力とループ表示を制御しています。


3. App.vue で表示

<template>
  <TodoApp />
</template>

<script setup>
import TodoApp from './components/TodoApp.vue'
</script>

4. CORS について

Spring Boot 側の Controller に

@CrossOrigin(origins = "http://localhost:5173")

を追加しておきましょう!


おわりに

これで、Vue 側の画面作成 & Spring Boot API 連携が完了です!

次回は、このシンプルアプリ開発を振り返って、今後の発展も考えてみます!

次回:https://qiita.com/ryusei_engineer/items/695e198a4a9f6e75b45b


この記事が良かったら、ストックやいいねをしてもらえると嬉しいです!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?