0
7

More than 3 years have passed since last update.

LaravelとVue.jsの連携

Last updated at Posted at 2020-08-28

LaravelとVue.jsの連携

Qiita初投稿です。
最近覚えることが多いのでアウトプットしていきながら理解を深めようと思います。

環境

  • PHP 7.3.11
  • laravel/framework 6.2
  • vue 2.6.11

手順

  1. Laravelプロジェクトの作成
  2. laravelとVue.jsの連携
  3. 立ち上げ

Laravelプロジェクトの作成

Composerのインストールに関しては完了している前提で書いております。

まずlaravelのプロジェクトを作成していきます。
下記のコマンドを実行しましょう。プロジェクト名は自分のプロジェクト名に変えてください。

$ composer create-project --prefer-dist laravel/laravel プロジェクト名

プロジェクト作成が完了したら

$ cd プロジェクト名

cdコマンドで該当プロジェクトまで移動します。
そしてローカルサーバーを立ち上げるために下記のコマンドを実行します。

$ php artisan serve

スクリーンショット 2020-08-27 0.05.02.png

この画面が出ていれば成功です。

laravelとVue.jsの連携

次にlaravelとVue.jsの連携を行います。

まずはじめlaravel/uiパッケージのインストールをします。

$ composer require laravel/ui

使用するUIタイプは bootstrap, vue, react から選べます。
今回はVue.jsを使用するのでvueを選択しますので下記のコマンドを実行します。

$ php artisan ui vue
$ npm install 

次に下記コマンドを実行

$ npm run dev

この画像のようにコンパイルできていれば成功です。
スクリーンショット 2020-08-28 15.17.35.png

次にresources/views/welcome.blade.phpを編集します。

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
*この行を追記<meta name="csrf-token" content="{{ csrf_token() }}">
        <title>Laravel</title>

        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
*この行を追記<script src="{{ asset('js/app.js') }}" defer></script>
    </head>
    <body>
     *不要なコードを削除しこの部分だけ残す
        <div id="app"></div>
    </body>
</html>

次にroutes/web.phpを編集します。

*こちらのコードを編集*
Route::get('/', function () {
    return view('welcome');
});

上のコードを下記に修正します。

*編集後*
Route::get('/{any?}', function () {
    return view('welcome');
})->where('any', '.*');

anyを設定することで"/"へアクセスするとwelcome.blade.phpが表示されるようにしています。しかしこれだけだと不十分で"/"へアクセスするとNot Foundになってしまいます。なのでweb.phpの一番最後の行の
->where('any', '.*')を追記しています。

vue-routerのインストールとセットアップ

まずはじめにvue-routerをインストールします。

$ npm install vue-route

次にresources/jsの直下にroutes.jsを作成,編集します。

router.js

import ExampleComponent from "./components/ExampleComponent";
import VueRouter from "vue-router";

const routes = [
    {
        path: "/",
        component: ExampleComponent,
        name: "home"
    }
];

const router = new VueRouter({
    routes,
});

export default router;

そしてresources/js/app.jsも編集します。

require('./bootstrap');

import router from "./routes";
import VueRouter from "vue-router";

window.Vue = require('vue');

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

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

今回はデフォルトで用意されているExampleComponent.vueを"/"で表示します。

resources/js/components/ExampleComponent.vue

<template>
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">laravelとVueの連携</div>

                <div class="card-body">
                    I'm an example component.
                </div>
            </div>
        </div>
    </div>
</div>
</template>

<script>
export default {
    mounted() {
        console.log('Component mounted.')
    }
}
</script>

ここまで出来ましたら次はwelcome.blade.phpを編集していきます。

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <title>Laravel</title>

        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
    <script src="{{ asset('js/app.js') }}" defer></script>
    </head>
    <body>
        <div id="app">
            **ここから追記**
            <router-view></router-view>
            **ここまで追記**
        </div>
    </body>
</html>

ここではを追記しました。
これによりpathが一致する場合にコンポーネント内にレンダリングされます。

立ち上げ

ここまで出来たらローカルサーバーを立ち上げて確認してみましょう。

$ npm run dev

を実行します。

ExampleComponent.vueが表示されていれば連携完了です。
"#"がついているのはvue.jsのmodeがデフォルトでhashになっているからです。
これを取り除くにはmodeをhistoryに変更する必要があります。これは簡単ですが次回以降やっていこうと思います。

スクリーンショット 2020-08-28 16.23.11.png

参考文献:Laravel6.xのインストール

0
7
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
7