Laradoc環境のLaravelとVueを導入済みの前提で進めます。
目次[非表示]
VueRouterをインストール
以下のコマンドを実行してVueRouterをインストール。
1 | npm install vue-router |
VueRouterを使用する
Laravelルーティングの設定を変更
Laravel用にルーティングを変更します。
Laravel側は全てindex.phpを返却しないとLaravel側にもルーティングの用意する必要があります。
※直接URLを入力された場合の対策
1 2 3 4 5 6 | <?php Route::get( '/{any}' , function () { // return view('welcome'); return view( 'vue' ); })->where( 'any' , '.*' ); |
コンポーネントの作成
コンポーネントファイルの作成。
VueRouterの動作確認のために2ファイル作成します。
1 2 3 4 5 6 7 | < template > < div > < p > < router-link to = '/world' >Hello</ router-link > </ p > </ div > </ template > |
1 2 3 4 5 6 7 | < template > < div > < p > < router-link to = '/hello' >World</ router-link > </ p > </ div > </ template > |
app.jsの編集
app.jsのを編集。
VueRouterの設定を入れます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import Vue from 'vue' import VueRouter from 'vue-router' require( './bootstrap' ); Vue.use(VueRouter); const router = new VueRouter({ mode: 'history' , relative: true , routes: [ { path: '/' , component: require( './components/Hello.vue' ). default }, { path: '/hello' , component: require( './components/Hello.vue' ). default }, { path: '/world' , component: require( './components/World.vue' ). default }, ] }); new Vue({ router, }).$mount( '#app' ); |
Viewの作成
Viewの作成
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!DOCTYPE html> < html lang = "{{ config('app.locale')}}" > < head > < meta charset = "utf-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1" > < meta name = "csrf-token" content = "{{ csrf_token() }}" > < title >Laravel + Vue</ title > < link rel = "stylesheet" href = "{{ asset('css/app.css') }}" > < base href="<?php echo url('/');?>"> </ head > < body > < div id = "app" > < router-view ></ router-view > </ div > < script src = "{{ asset('js/app.js') }}" ></ script > </ body > </ html > |
実行
以下のコマンドを実行するとタスクが実行します。
1 2 3 4 5 6 7 8 9 10 11 | // 全タスク実行 npm run dev // 全タスク実行を実行し、出力を圧縮 npm run production // アセットの変更監視 npm run watch // アセットの変更監視( watch が効かない場合) npm run watch -poll |
最後にhttps://localhost/public/helloにアクセスしたら画面が出ます。
わかりづらいですがVueRouterを使って遷移しています。
まとめ
VueRouterを導入することフロント側とサーバーサイド側に切り分けが可能になります。
これによりRESTfulな作りにすることが可能です。
0 件のコメント :
コメントを投稿