LoginSignup
2
1

More than 3 years have passed since last update.

Laravel + Vue-cliを使用した SPAの構築

Last updated at Posted at 2020-06-18

バージョンを指定してLaravelのプロジェクトを作成

  composer create-project "laravel/laravel=6.*" laravel_sample

サーバーを起動させる 

プロジェクトディレクトリに移動

 cd laravel_sample

下記コマンドを打つ

  php artisan serve  

サーバー起動後、( http://localhost:8000 )にアクセスしてLaravelのTOP画面が表示されていればOK

Vue-cliプロジェクトとLaravelとの連携 

Vueをnodeの(npm)を使用してローカルインストール
npm install --save-dev vue-cli
作成済みのlaravelのディレクトリに移動してVue-cliのプロジェクトを作成 

①プロジェクト作成する為下記コマンドを入力。

vue create vue_sample

②インストール方法をdefaultかManuallyかを選択します。
   (今回はSPAを構築するのでManuallyを選んでください。)

Vue CLI v*.*.*
 ? Please pick a preset:
   default (babel, eslint)
 > Manually select features

③必要な機能を選択します。
   (今回はBabel・Router・Linterの3個を選択します)

? Check the features needed for your project:
>(*) Babel
 ( ) TypeScript
 ( ) Progressive Web App (PWA) Support
 (*) Router
 ( ) Vuex
 ( ) CSS Pre-processors
 (*) Linter / Formatter
 ( ) Unit Testing
 ( ) E2E Testing

Use history mode for router? (Requires proper server setup for index fallback in production): Yes

? Pick a linter / formatter config: Basic

? Pick additional lint features: Lint on save

? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? In dedicated config files

Vueで Single Page アプリケーションの作成準備
├─src/
 ├─assets/
 ├─components/
  ├─router/
 ├─views/
 ├─App.vue           
  └─main.js
Vueアプリケーションをlaravel上で立ち上げる 

①プロジェクト直下に配置されている(public)ディレクトリのindex.htmlファイルをプロジェクト直下のディレクトリに置き直しファイル名をbase.htmlに変更

②Vue.config.jsファイルを作成し下記のように変更

module.exports = {

    outputDir: '../public/app',

    publicPath: '/app',

    // src
    pages: {

        src: {
            entry: 'src/main.js',
            template: 'templates/base.html',
            filename: '../../resources/views/spa/apli.blade.php',
        },
    },
};
Vue-cli側で作成したコードを配信する為にlaravel側に新たにControllerを作成
 php artisan make:controller SpaController

作成したcontrollerファイルに下記のコードを追記

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SpaController extends Controller
{
    public function app()
    {
        return view('spa/apli');
    }
}
laravel側のroutes/web.phpファイルに下記のルートを追記
Route::get('/apli{any}', 'SpaController@app')->where('any', '(/?$|/.*)');
Vue-cliのディレクトリに移動して ビルドする
npm run build
配信されるURLを整える

プロジェクト名\src\router\index.jsを下記のように変更

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,

 ↓↓↓

export default new Router({
  mode: 'history',
  base: '/apli/', 

ラストに Vueのプロジェクトのディレクトリにてnpm run build でビルドをして完了です。

確認の為アクセスしてみましょう。

URL( http://localhost:8000/apli)

アクセス時VueのTOP画面が表示されていればOK

こちらのサイダス技術者ブログさんを参考に記事を書いています(https://tech.cydas.com/entry/vue-laravel-mspa1)

2
1
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
2
1