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?

API通信は、Vue.jsアプリケーションにおいて外部データを取得したり、サーバーと通信するために重要な役割を果たします。この記事では、Axiosを使用したHTTPリクエスト、RESTful APIの統合、GraphQLとVue.js、リアルタイムデータの取得について記述します。

目次

  1. Axiosを使ったHTTPリクエスト
  2. RESTful APIの統合
  3. GraphQLとVue.js
  4. リアルタイムデータの取得(WebSocketとSocket.io)

1. Axiosを使ったHTTPリクエスト

Axiosは、PromiseベースのHTTPクライアントであり、Vue.jsアプリケーションでよく使用されます。まず、Axiosをプロジェクトにインストールします。

インストール

npm install axios --save

基本的な使用例

以下は、Axiosを使用してAPIからデータを取得する基本的な例です。

src/components/FetchData.vue

<template>
  <div>
    <h1>Data from API</h1>
    <ul>
      <li v-for="item in items" :key="item.id">{{ item.name }}</li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      items: []
    };
  },
  created() {
    axios.get('https://api.example.com/items')
      .then(response => {
        this.items = response.data;
      })
      .catch(error => {
        console.error('There was an error!', error);
      });
  }
};
</script>

2. RESTful APIの統合

RESTful APIをVue.jsアプリケーションに統合する方法を解説します。以下の例では、CRUD(作成、読み取り、更新、削除)操作を行います。

データの取得

src/components/ItemList.vue

<template>
  <div>
    <h1>Items</h1>
    <ul>
      <li v-for="item in items" :key="item.id">{{ item.name }}</li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      items: []
    };
  },
  created() {
    this.fetchItems();
  },
  methods: {
    fetchItems() {
      axios.get('https://api.example.com/items')
        .then(response => {
          this.items = response.data;
        })
        .catch(error => {
          console.error('Error fetching items:', error);
        });
    }
  }
};
</script>

データの作成

src/components/AddItem.vue

<template>
  <div>
    <h1>Add Item</h1>
    <form @submit.prevent="addItem">
      <input v-model="newItem" placeholder="Item name">
      <button type="submit">Add</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      newItem: ''
    };
  },
  methods: {
    addItem() {
      axios.post('https://api.example.com/items', { name: this.newItem })
        .then(() => {
          this.newItem = '';
          this.$emit('item-added');
        })
        .catch(error => {
          console.error('Error adding item:', error);
        });
    }
  }
};
</script>

データの更新

src/components/EditItem.vue

<template>
  <div>
    <h1>Edit Item</h1>
    <form @submit.prevent="updateItem">
      <input v-model="item.name" placeholder="Item name">
      <button type="submit">Update</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  props: ['itemId'],
  data() {
    return {
      item: {}
    };
  },
  created() {
    this.fetchItem();
  },
  methods: {
    fetchItem() {
      axios.get(`https://api.example.com/items/${this.itemId}`)
        .then(response => {
          this.item = response.data;
        })
        .catch(error => {
          console.error('Error fetching item:', error);
        });
    },
    updateItem() {
      axios.put(`https://api.example.com/items/${this.itemId}`, this.item)
        .then(() => {
          this.$emit('item-updated');
        })
        .catch(error => {
          console.error('Error updating item:', error);
        });
    }
  }
};
</script>

データの削除

src/components/DeleteItem.vue

<template>
  <div>
    <button @click="deleteItem">Delete</button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  props: ['itemId'],
  methods: {
    deleteItem() {
      axios.delete(`https://api.example.com/items/${this.itemId}`)
        .then(() => {
          this.$emit('item-deleted');
        })
        .catch(error => {
          console.error('Error deleting item:', error);
        });
    }
  }
};
</script>

3. GraphQLとVue.js

GraphQLは、クライアントが必要なデータを正確に取得できるようにするクエリ言語です。Apollo Clientを使用して、Vue.jsアプリケーションにGraphQLを統合します。

インストール

npm install @apollo/client graphql vue-apollo --save

Apollo Clientの設定

src/apollo-client.js

import { ApolloClient, InMemoryCache } from '@apollo/client';
import { createHttpLink } from 'apollo-link-http';

const httpLink = createHttpLink({
  uri: 'https://api.example.com/graphql'
});

const cache = new InMemoryCache();

const apolloClient = new ApolloClient({
  link: httpLink,
  cache
});

export default apolloClient;

Vue Apolloの設定

src/main.js

import Vue from 'vue';
import App from './App.vue';
import VueApollo from 'vue-apollo';
import apolloClient from './apollo-client';

Vue.use(VueApollo);

const apolloProvider = new VueApollo({
  defaultClient: apolloClient
});

new Vue({
  apolloProvider,
  render: h => h(App)
}).$mount('#app');

データの取得

src/components/GraphQLData.vue

<template>
  <div>
    <h1>GraphQL Data</h1>
    <ul>
      <li v-for="item in items" :key="item.id">{{ item.name }}</li>
    </ul>
  </div>
</template>

<script>
import gql from 'graphql-tag';

export default {
  data() {
    return {
      items: []
    };
  },
  apollo: {
    items: {
      query: gql`
        query {
          items {
            id
            name
          }
        }
      `
    }
  }
};
</script>

4. リアルタイムデータの取得(WebSocketとSocket.io)

リアルタイムデータの取得には、WebSocketを使用します。ここでは、Socket.ioを使用した例を紹介します。

インストール

npm install socket.io-client --save

Socket.ioの使用

src/components/RealTimeData.vue

<template>
  <div>
    <h1>Real-Time Data</h1>
    <ul>
      <li v-for="message in messages" :key="message.id">{{ message.text }}</li>
    </ul>
  </div>
</template>

<script>
import io from 'socket.io-client';

export default {
  data() {
    return {
      socket: null,
      messages: []
    };
  },
  created() {
    this.socket = io('http://localhost:3000');
    this.socket.on('message', (message) => {
      this.messages.push(message);
    });
  },
  beforeDestroy() {
    this.socket.disconnect();
  }
};
</script>

まとめ

この記事では、Vue.jsを使用したAPI通信とデータ取得について記述しました。Axiosを使用したHTTPリクエスト、RESTful APIの統合、GraphQLの使用、リアルタイムデータの取得について学びました。これらの技術を駆使して、よりインタラクティブでデータ駆動型のアプリケーションの構築を目指します。

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?