【Laravel5.8 + Vue】Laravel5.8でVue.jsを使ってみたい

今回はLaravelのプロジェクトインストールから説明を。

プロジェクトインストール

$ laravel new laravel-vue

package.jsonの編集

以下、一項目を追加し、devDependenciesの全体像を確認してください。

//追加
"vue-template-compiler": "^2.6.10"
    "devDependencies": {
        "axios": "^0.19",
        "bootstrap": "^4.1.0",
        "cross-env": "^5.1",
        "jquery": "^3.2",
        "laravel-mix": "^4.0.7",
        "lodash": "^4.17.13",
        "popper.js": "^1.12",
        "resolve-url-loader": "^2.3.1",
        "sass": "^1.15.2",
        "sass-loader": "^7.1.0",
        "vue": "^2.5.17",
        "vue-template-compiler": "^2.6.10"
    }

npm installでpackage.jsonの中身をインストール

$ npm install
こんなログが出ます
ec2-user:~/environment/laravel-vue $ npm install

> core-js-pure@3.1.4 postinstall /home/ec2-user/environment/laravel-vue/node_modules/core-js-pure
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: 
> https://opencollective.com/core-js 
> https://www.patreon.com/zloirock 

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

added 1008 packages from 483 contributors and audited 17137 packages in 24.66s
found 0 vulnerabilities

npm run devでビルドする

インストールしただけではVue.jsが動かないため、ビルドします。

$ npm run dev
なぜビルドしないとVueは動かない?
$ npm run dev

を行うことによって、Vueを動作させる

  • /public.js/app.js
  • /public/css/app.css

をロードすることができます。

時間がある時にこの2つのファイルの中身を確認してみてください。かなり複雑なコードが書かれているため、Vueを動かすのに必要であるということだけは理解できます。

/resources/views/welcome.blade.phpを編集

最初からルーティングがなされているため、こちらのbladeファイルをVueのComponentを表示させるのに利用しましょう。

<!DOCTYPE html>
<html lang="ja">
    <head>
        <title>Index</title>
                    <!--/resoces/css/ と /public/css/ のCSSファイルを読み込む-->
        <link href="{{ mix('css/app.css') }}" rel="stylesheet" type="text/css">
        <!--LaravelでVueを使用する際のお約束!-->
        <meta name="csrf-token" content="{{ csrf_token() }}">
    </head>
    <body>
        <h1>Hello/Index</h1>
        <p>{{$msg}}</p>
        
        <!--VueのComponentを読み込むためにはappというidのdiv要素を配置する-->
        <div id="app">
            <!--「appというidのdiv要素」の中にcomponentの設置-->
            <example-component />
        </div>
         <!--/resoces/js/ と /public/js/ のJSファイルを読み込む-->
         <!--コンテナタグ(= <div id="app"> )の後に記述する-->
        <script src="{{ mix('js/app.js') }}"></script>
    </body>
</html>


以下にコメントの補足をしておきますね。

/resoces/css/ と /public/css/ のCSSファイルを読み込む
<link href="{{ mix('css/app.css') }}" rel="stylesheet" type="text/css">

Vueで使用する/public/css/ディレクトリ内のファイルと、Laravelで使用する/resoces/css/ディレクトリのファイルを1つに合わせてくれるのがこちらの関数です。

Laravelmixが使用されています。

csrf LaravelでVueを使用する際のお約束
<meta name="csrf-token" content="{{ csrf_token() }}">

LaravelではFormでおなじみのCSRFトークンですが、Vueを使用する際には読み込むようにしましょう。

なくても画面表示に支障はないようですが、Consoleで警告が出ます。

appというidのコンテナタグを配置
        <div id="app">

        </div>

もはやVueを使っている人にはおなじみのもの。Componentを表示させる際にはこちらのコンテナタグを用意します。

componentの設置
<example-component />

Laravelにはデフォルトで、/resources/js/components/ExampleComponent.vueが用意されているため、こちらを使用しました。

***/resources/js/app.jsの中身は?

/resources/js/app.jsは、VueのComponentやVue Routerのインスタンスrouter、Vuexのstoreなどをルートコンポーネントに登録するためのファイルです。

ちょうど、Vue CLIでインストールしたパッケージの/src/main.jsに当たる役割をしています。

app.jsの中身を抜粋してみると、

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i);
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

const app = new Vue({
    el: '#app',
});

このように書かれていましたが、簡単に支持されていることを書くと、
「使いたいComponentを登録して、#appの付いているコンテナタグに表示させるよ」
と言っているようです。

こちらでComponent登録の際には、

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

こちらの書き方に倣って、Componentを登録すればいいはずです。

-/resoces/js/ と /public/js/ のJSファイルを読み込む
<script src="{{ mix('js/app.js') }}"></script>

先ほどのCSSファイルで使用したmixと同様の考え方でOKです。

Controllerの作成

Laravel側でページ表示のためのContorollerとアクションを設定していきます。

$ php artisan make:Controller HelloController
HelloController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HelloController extends Controller
{
    public function index () {
        $data = [
            'msg' => 'This is Vue.js applications!',
            ];
        return view('welcome',$data);
    }
}

web.phpの修正

ルーティングを修正します。

Route::get('/', 'HelloController@index');

再びnpm run build

$ npm run build

ファイルに修正を加えたら都度、npm run buildが必要だということをお忘れなく

npm run watchが便利
$ npm run watch

ファイル修正のたびにnpm run buildは面倒ですよね。
そこでnpm run watchの出番です。

watchを走らせておけば、スタイルシートスクリプトファイルが変更されるごとにページに反映されるんです!

サーバの起動

// 実行環境によって違うかも
$ sudo service mysqld start
$ php artisan serve --port 8080

残りはLaravelのサーバ起動だけです!

これで画面にVueのComponentが反映されているか確認してみてくださいね。
f:id:nekorokkekun:20190803182342p:plain