はじめに
前回の記事でLaravelでREST APIを作りました。
EC2のLaravel6.0環境でRest APIを準備する AWS/Laravel連載(9)
今回はAPI経由で投稿一覧表示部分をVue.js+axiosで実装します。
Vue, axiosを入れる
Laravelのpackage.jsonは最初からVue.jsとaxiosが入っているのでnpm installだけでOKです。
$ npm install
Vue部分を書きます。
resources/js/app.js
...
const app = new Vue({
  el: '#app',
  data: {
    posts: []
  },
  methods: {
    fetchPosts: function(){
      axios.get('/api/posts').then((res)=>{
        this.posts = res.data
      })
    }
  },
  created() {
    this.fetchPosts()
  },
});
上記保存したらビルドが必要です。
$ npm run dev
終わるとpublic/js/app.jsに書き出されます。
viewを修正
resources/views/home.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Dashboard</div>
                <div class="card-body">
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif
                    @{{ posts.total }}件
                    <table class="table">
                        <thead>
                            <tr>
                            <th>ID</th>
                            <th>タイトル</th>
                            <th>本文</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="post in posts.data" v-bind:key="post.id" v-cloak>
                                <td>@{{ post.id }}</td>
                                <td>@{{ post.title }}</td>
                                <td>@{{ post.content }}</td></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
v-forはVue.jsでのfor文です。
app.jsの中で、APIから取ってきた投稿一覧(ページャー付き)をpostsという変数に入れています。
posts.dataの中身(配列)をループしpostという変数に入れ、件数分を表示しています。
連載10.5回という形で、Vueの開発がしやすくなるツールを紹介しています。
ぜひご確認ください。
EC2のLaravel6.0環境 VueとLaravelでのTIPS AWS/Laravel連載(10.5)