13
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

laravel で vue.js , axios を使う

Last updated at Posted at 2019-01-07

npm install やらなんやら。
わけわからんし、超面倒。
直接読み出そうぜ。

まずはルーティング。
・/api/test/ にアクセスしたらデータを取得。
・それ以外はすべて welcome.blade.php に来るようにする。

welcome.blade.php

<?php
Route::prefix('api')->group(function() {
    Route::get('test','NikkiController@test');
});

Route::get('/{app}', function () {

    \File::cleanDirectory(storage_path()."/framework/views/");//キャッシュがうざいので毎回削除する。本番ではこれを消す。
    return view('welcome');
})->where('app', '.*');
?>

Http/Controllers/NikkiController.php

    public function test()
    {
        $res = Nikki::query()
            ->select('id','title')
            ->get();
        return $res;
    }


welcom.blade.php

<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel-Vue-todo</title>
</head>
<body>


<div id="app">
    <button @click="request">データ取得</button>
    <ul >
        <li v-for="item in items">@{{ item.title }}</li>
    </ul>
</div>




<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script>
    const app = new Vue({
        el: '#app',
        data: {
            items: [] //データ格納
        },
        methods: {
            request: function(){ //←axios.getでデータを取得
                axios.get('/api/test').then((res)=>{
                    console.log(res.data);
                    this.items = res.data //取得したデータをitemsに格納
                })
                    .catch(error => console.log(error))
            }
        },
        // created() {  //最初にメソッドを実行
        //     this.request()
        // },
    });
</script>

</body>
</html>

たったこれだけでOK。

13
17
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
13
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?