LoginSignup
0
0

More than 3 years have passed since last update.

なるはや Vue SPA入門:API コール

Last updated at Posted at 2019-08-04

Vue CLI3 で作成した SPA(Single Page Application)プロジェクト上で、段階的に Vue.js を学んで行きましょう。

目次はこちら

今回は API コール編です。

前提事項

ライフサイクル編 が完了していること。

json ファイルの追加

public/todos.json ファイルを追加します。

public/todos.json
{
  "todos": [
    { "id": 1, "text": "Learn Vue" },
    { "id": 2, "text": "Learn about single file components" },
    { "id": 3, "text": "Learn about conponents" }
  ]
}

TodoList.vue の修正

created() ライフサイクルフックで fetch() を使い Todo リスト(json)を取得します。
※ ここでは、直接 json ファイルを読み込んでいますが、REST API 等で json を取得するのと全く同じ処理になります。

src/views/TodoList.vue
// ...
export default {
  // ...
  data() {
    return {
      todos: []
    };
  },
  created() {
    fetch("http://localhost:8080/todos.json")
      .then(response => response.json())
      .then(json => {
        console.log(json);
        this.todos = json.todos;
      })
      .catch(error => console.error("Error:", error));
  },
  // ...
};

動作確認

http://localhost:8080/todolist にアクセスして、Todo リストが表示されれば OK です。API 経由で取得した json の内容がデベロッパーツールのコンソールログに表示されているはずです。

api.png

次回

Vuex モジュール

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