実践練習

このセクションでは、Nuxt.js 3を使用して、実際のプロジェクトを一から構築するプロセスを詳細に説明します。プロジェクトのテーマとしては、「レシピ共有アプリケーション」を考えます。このアプリケーションでは、ユーザーは様々なレシピを閲覧、投稿、お気に入り登録することができます。

1. プロジェクトのセットアップ

  1. Nuxt.js 3プロジェクトのセットアップを行います。
    npx nuxi init recipe-app
    cd recipe-app
    npm install
    
  2. 必要な依存関係(例えば、Axios、Piniaなど)をインストールします。
    npm install @pinia/nuxt axios
    

2. ディレクトリ構造の設定

以下のような基本的なディレクトリ構造を設定します。

  • components/: UIコンポーネントを格納します。
  • pages/: アプリケーションのページを格納します。
  • composables/: 再利用可能なロジックを格納します。
  • stores/: Piniaストアを格納します。
  • assets/: スタイルシートや画像などを格納します。

3. ページの作成

pages/index.vueを作成し、レシピの一覧を表示するホームページを作成します。

<template>
  <div>
    <h1>レシピ一覧</h1>
    <RecipeList :recipes="recipes" />
  </div>
</template>

<script setup>
import RecipeList from '@/components/RecipeList.vue'
import { useRecipeStore } from '@/stores/recipe'

const recipeStore = useRecipeStore()
const recipes = computed(() => recipeStore.recipes)
</script>

4. ストアとComposablesの設定

Piniaストア(stores/recipe.js)を使用して、レシピの状態を管理します。

import { defineStore } from 'pinia'
import axios from 'axios'

export const useRecipeStore = defineStore('recipe', {
  state: () => ({
    recipes: [],
  }),
  actions: {
    async fetchRecipes() {
      const response = await axios.get('https://api.example.com/recipes')
      this.recipes = response.data
    },
  },
})

5. コンポーネントの作成

components/RecipeList.vueコンポーネントを作成し、レシピのリストを表示します。

<template>
  <ul>
    <li v-for="recipe in recipes" :key="recipe.id">
      {{ recipe.title }}
    </li>
  </ul>
</template>

<script setup>
defineProps({
  recipes: Array,
})
</script>

6. スタイリング

assets/main.cssにグローバルスタイルを追加し、アプリケーションに統一感のある外観を提供します。

body {
  font-family: 'Helvetica', sans-serif;
  margin: 0;
  padding: 0;
}
h1 {
  color: #333;
}

7. データフェッチングと表示

ホームページがマウントされたときに、レシピデータをフェッチするようにします。

<script setup>
import { onMounted } from 'vue'
import { useRecipeStore } from '@/stores/recipe'

const recipeStore = useRecipeStore()

onMounted(async () => {
  await recipeStore.fetchRecipes()
})
</script>

8. ルーティングとナビゲーション

追加のページ(例えば、レシピの詳細ページ、レシピ投稿ページなど)を作成し、pages/ディレクトリに配置します。Nuxt.jsはこれらのファイルを自動的にルートに変換します。

9. デプロイメント

開発が完了したら、作成したアプリケーションをVercel, Netlify, AWS Amplifyなどのプラットフォームにデプロイします。