1
2

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】Vue 3 を要素別に学ぶ:ページ構成・コンポーネント・データ取得の基本

Posted at

はじめに

Vue.js は、軽量で学習コストが低く、コンポーネントベースの UI 開発に適した JavaScript フレームワークです。Vue 3 では Composition API の導入やパフォーマンスの向上が行われ、よりスケーラブルなアプリケーション開発が可能になりました。

この記事では、Vue 3 の概要、基本的な使い方、環境構築からコンポーネント・ルーティング・状態管理など、Vue 単体でのアプリケーション開発の基礎を解説します。

プロジェクトの作成

以下のコマンドでプロジェクトを作成します。

npm create vue@latest

途中インストールオプションが提示されます。
今回は以下の選択をしました。

│  ◼ TypeScript
│  ◻ JSX Support
│  ◼ Router (SPA development)
│  ◻ Pinia (state management)
│  ◻ Vitest (unit testing)
│  ◻ End-to-End Testing
│  ◼ ESLint (error prevention)
│  ◼ Prettier (code formatting)

その後、以下のコマンドでローカルサーバーを起動します。

cd vue-sample
npm install
npm run dev

http://localhost:5173 にアクセスすると、Vue のスタート画面が表示されます。

image.png

ディレクトリ構造の概要

プロジェクトを作成すると、以下のような構成が生成されます。

ディレクトリ 説明
src/ アプリケーション本体のコード
src/components/ 再利用可能な UI コンポーネント
src/views/ ページ単位のビューコンポーネント(Vue Router 使用時)
src/router/ ルーティング定義(Router を選択した場合)
src/stores/ 状態管理(Pinia を選択した場合)
public/ 静的アセットの配置先

ページの作成とルーティング

Vue Router を導入すると、ページ間の移動が可能になります。

ページ用のコンポーネントは先述の通り src/views/ に配置します。

src/views/AboutView.vue
<template>
  <div class="about">
    <h1>This is an about page</h1>
  </div>
</template>

<style>
@media (min-width: 1024px) {
  .about {
    min-height: 100vh;
    display: flex;
    align-items: center;
  }
}
</style>

上記コンポーネントを src/router/index.ts で読み込みます。

src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
  ],
})

export default router

加えて、上記のルーティングファイルを src/main.ts で読み込むことでルーティングの実装ができます。

src/main.ts
import { createApp } from 'vue'
import App from './App.vue'
import { router } from './router'

createApp(App).use(router).mount('#app')

image.png

コンポーネントの作成と読み込み

Vue 3 では、<script setup> 構文を使うことで、より簡潔で直感的なコンポーネント記述が可能になりました。

<script setup> とは?

<script setup> 構文は、Composition API をよりシンプルに記述できる構文です。通常の Composition API と比べて以下のようなメリットがあります。

  • より短く、直感的に書ける
  • definePropsdefineEmits などが自動的に型推論される
  • setup() 関数を書く必要がない(すべては自動で setup() の中に展開される)
sample.vue
<script setup lang="ts">
const message = 'Hello'
</script>

<template>
  <p>{{ message }}</p>
</template>

この構文を使えば、従来の export defaultsetup() 関数を明示的に書く必要がなくなり、ロジックとテンプレートの対応関係も明確になります。

コンポーネントの作成

h2 タグに「Hello World」、p タグ親コンポーネントから受け取った msg を表示するコンポーネントを作成します。

src/components/HelloWorld.vue
<script setup lang="ts">
defineProps<{ msg: string }>()
</script>

<template>
  <div class="hello">
    <h2>Hello World</h2>
    <p>{{ msg }}</p>
  </div>
</template>

<style scoped>
.hello {
  color: #42b983;
  font-weight: bold;
}
</style>

コンポーネントの読み込み

作成したコンポーネントを AboutView.vue で以下のように読み込むと表示できます。

About.vue
<script setup lang="ts">
import HelloWorld from '@/components/HelloWorld.vue'
</script>

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <HelloWorld msg="This is Vue3!" />
  </div>
</template>

<style>
@media (min-width: 1024px) {
  .about {
    min-height: 100vh;
    display: flex;
    align-items: center;
  }
}
</style>

image.png

外部データの取得

Vue 3 では、fetchaxios などを使って簡単に外部 API からデータを取得できます。今回は <script setup> 構文と Composition API を使って、API からデータを取得して画面に表示します。

axios のインストール

まずは HTTP クライアントライブラリである axios をインストールします。

npm install axios

サンプル API の利用

今回は以下の JSON プレースホルダー API を使って、仮の投稿データを取得してみます。

サンプルコンポーネントの作成

外部 API から取得したデータをリスト表示するコンポーネントを作成します。

PostList.vue
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import axios from 'axios'

type Post = {
  id: number
  title: string
  body: string
}

const posts = ref<Post[]>([])
const isLoading = ref(true)
const err = ref('')

// コンポーネントマウント時にデータ取得
onMounted(async () => {
  try {
    const response = await axios.get<Post[]>('https://jsonplaceholder.typicode.com/posts')
    posts.value = response.data
  } catch (error) {
    err.value = 'Failed to getting data:' + JSON.stringify(error)
  } finally {
    isLoading.value = false
  }
})
</script>

<template>
  <div>
    <h2>投稿一覧</h2>

    <p v-if="isLoading">読み込み中...</p>
    <p v-if="err">{{ err }}</p>

    <ul v-else>
      <li v-for="post in posts" :key="post.id">
        <h3>{{ post.title }}</h3>
        <p>{{ post.body }}</p>
      </li>
    </ul>
  </div>
</template>

<style scoped>
h2 {
  color: #2c3e50;
  margin-bottom: 1rem;
}

li {
  margin-bottom: 1rem;
}
</style>

コンポーネントの読み込み

作成したコンポーネントを PostVie.vue で読み込みます。

PostsView.vue
<script setup lang="ts">
import PostList from '@/components/PostList.vue'
</script>

<template>
  <main>
    <h1>This is a PostsView page</h1>
    <PostList />
  </main>
</template>

APIから取得した値が画面に表示されます。

image.png

まとめ

Vue 3 は、軽量で学習コストが低い JavaScript フレームワークで、Composition API やパフォーマンスの向上、コンポーネントベースの UI 開発など、モダンな Web アプリケーション開発を強力にサポートしてくれます。

この記事では、Vue プロジェクトの作成からページの作成とルーティング、コンポーネントの使い方、外部データの取得方法まで、基本的な流れを一通り紹介しました。

参照

関連記事

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?