LoginSignup
21
21

More than 3 years have passed since last update.

laravelでvue-routerの設定方法

Last updated at Posted at 2019-09-30

はじめに

今回はvue-rounterのみのURLを使用した場合のlaravelとvue.jsの設定についての記事になりますので、
laravelとvue.jsの環境が整っている事が前提となっています。

vue-routerのインストールからコンパイルまでの記事になっていますので、
実際に使用方法を知りたい方はこちらを参照ください。
https://qiita.com/KARENN/items/03b5881bb6e8e521ad11

今回使用するファイル構成

projectName
 ↳routes
  ↳web.php
 ↳resorces
  ↳js
   ↳app.js
   ↳router.js
   ↳components
    ↳samaple.vue
  ↳views
   ↳index.blade.php
 ↳webpack.mix.js

インストール

npm install vue-router

laravelのルーティングファイル

web.php(vue-routerのみ)
Route::get('/{any}', function () {
    return view('index');
})->where('any', '.*');

この記述をしておくことで「/」の後のURLは全てvue-rounterで指定した内容を読み込んでくれることになります。
この記述がなければ、vue-rounterを使用してもlaravelのRouting設定が先に読まれることになりますので注意してください。
この書き方は全てのURLをvue-routerで使用したい場合の書き方ですので、
特定の条件を利用したい場合はこちらの記述をします。

web.php(laravelとvue-router)
Route::get('/', function () {
    return view('task.list');
})

Route::get('/member/{any}', function () {
    return view('member.list');
})->where('any', '.*');

このように書くと、/でアクセスするとタスク一覧はlaravelのルーティングとして認識されます。
/member配下のURLは全てvue-routerで指定したルーティングとして認識されるようになります。

vue.jsの設定

app.js
import Vue from 'vue' 追加
import router from './router' 追加

new Vue({
    el: '#app',
    router: router 追加
})

app.jsはVue.jsをインストールした際にデフォルトで追加されているファイルなので
そのファイルに対して上記の部分を追加してください。

ルーティングの設定

router.js
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter);

// コンポーネントをインポート
import index from './components/index.vue';
import detail from './components/detail.vue';

export default new VueRouter({
    // モードの設定
    mode: 'history',
    routes: [
        {
            // routeのパス設定
            path: '/',
            // 名前付きルートを設定したい場合付与
            name: index,
            // コンポーネントの指定
            component: index
        },
        {
            path: '/detail',
            name: detail,
            component: detail
        }
    ]
});

modeの設定はデフォルトではhashとなってますが、ここではhistoryを使用しています。
hashを使用している場合、下記のように#がrouteの中に入るので注意してください。
ex) /detailのルーティングの場合: http://localhost/#/detail

コンパイル

webpack.js
const mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/js/app.js', 'public/js')
    .js('resources/js/router.js', 'public/js') 追加
    .sass('resources/sass/app.scss', 'public/css');

npm run watchを再度行い、public/jsの下にrouter.jsがあればコンパイル成功となります。

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