Laravel 5.6 + Vue.js + axios , ajax 通信の追加。
index:
概要:
以前の Laravel 関連となり
Laravel 5.6で、Vue.js + axios の例となります。
環境とか
php7.1
Laravel 5.6
Vue.js
axios
axios など追加
・ vue.js の追加方法は、前回と同じです。
・base2.blade.php
親テンプレに、追加
git から、axios を取得。
https://github.com/axios/axios
フォルダは、下記で。axios.min.js
\axios-master\dist\axios.min.js
public\js
下に配置してます。
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script> <script src="{{ asset('js/axios.min.js') }}?A1"></script>
vue.js の実装
・コントローラ
TasksController.php
画面表示、 JSON出力
// public function test3() { $tasks = Task::orderBy('updated_at', 'desc')->get(); //var_dump($tasks ); return view('tasks/test3')->with('task', new Task()); } // public function api_test3() { $tasks = Task::orderBy('updated_at', 'desc')->get(); return response()->json( $tasks ); }
・view側 、test3.blade.php
v-for で、リスト追加しています。
@extends('layouts.base2') @section('title', 'タスク一覧') @section('content') <div class="panel panel-default"> <div class="panel-heading"> 一覧 </div> <div class="panel-body"> </div> </div> <hr /> <div> <!-- vue --> <h1>Test3</h1> <!-- <h3>vue test22:</h3> --> <div id="hello"> <p>Length: @{{ length }}</p> <ul> <li v-for="item in list"> id: @{{ item.id }}, ,name= @{{ item.name }} </li> </ul> </div> <!-- --> <script> var app = new Vue({ el: '#hello', data: { length: 0, pages: [] , list: [], }, created: function(){ axios .get('./api_test3') .then(response =>{ // success this.length = response.data.length; for(var i = 0; i < response.data.length; i++) { // console.log(response.data[i].id ); this.list.push(response.data[i] ); } }) } }); </script> @endsection
表示
=> 画面の起動時にリストの表示を、追加