Vue.jsは、柔軟で使いやすいフロントエンドフレームワークであり、外部データを動的に読み込むことも非常に簡単です。この記事では、JSONファイルからデータを取得し、Vue.jsアプリケーションで表示する方法を詳しく説明します。
JSONファイルの準備
プロジェクト内に、データを格納するためのJSONファイルを作成します。例えば、data.json という名前で以下のようにデータを記述します。
{
  "items": [
    { "id": 1, "name": "Item 1", "description": "This is item 1" },
    { "id": 2, "name": "Item 2", "description": "This is item 2" },
    { "id": 3, "name": "Item 3", "description": "This is item 3" }
  ]
}このファイルをプロジェクトの適切なディレクトリに保存します。
Vue.jsでのデータ取得方法
次に、Vue.jsを使ってこのJSONファイルからデータを取得する方法を紹介します。fetch APIを使用して、データを非同期で取得し、コンポーネントに反映します。
<template>
  <div>
    <h1>Items</h1>
    <ul>
      <li v-for="item in items" :key="item.id">
        <h2>{{ item.name }}</h2>
        <p>{{ item.description }}</p>
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  data() {
    return {
      items: []
    };
  },
  created() {
    // JSONファイルを取得
    fetch('/path/to/data.json')
      .then(response => response.json())
      .then(data => {
        this.items = data.items;
      })
      .catch(error => console.error('Error fetching JSON:', error));
  }
};
</script>このコードでは、fetchメソッドを使用してJSONファイルを取得し、そのデータをitems配列に格納しています。
axiosを使ったデータ取得方法
fetchの代わりに、より多機能なHTTPクライアントであるaxiosを使う方法もあります。まず、axiosをインストールし、その後にデータを取得します。
axiosのインストール
以下のコマンドでaxiosをインストールします。
npm install axiosaxiosを使ったデータ取得
次に、以下のようにaxiosを使ってデータを取得し、コンポーネントに表示します。
<template>
  <div>
    <h1>Items</h1>
    <ul>
      <li v-for="item in items" :key="item.id">
        <h2>{{ item.name }}</h2>
        <p>{{ item.description }}</p>
      </li>
    </ul>
  </div>
</template>
<script>
import axios from 'axios';
export default {
  data() {
    return {
      items: []
    };
  },
  created() {
    axios.get('/path/to/data.json')
      .then(response => {
        this.items = response.data.items;
      })
      .catch(error => console.error('Error fetching JSON:', error));
  }
};
</script>こちらのコードでは、axios.getメソッドを使ってJSONファイルからデータを取得し、そのデータをitems配列に格納しています。
まとめ
Vue.jsでJSONファイルからデータを取得する方法はとても簡単です。fetchやaxiosを使うことで、外部データを手軽に扱うことができます。適切なエラーハンドリングも行い、安定したアプリケーションを構築しましょう。

 
  
  
  
  