SPA(シングルページアプリケーション)、ついに足を踏み入れました。
ジャンルを問わず新しい事を始める時は大きなエネルギーが必要ですが、Vueはその辺りのハードルが低いので本当に助かります。
Vue自体の学習コストが低いということもあり、SPAを実現する為のライブラリ、Vue Routerも抵抗無く始められます。
環境
- Laravel 6.2
- Vue 2.5.17
LaravelにVueを導入する手順は以下の記事で解説していますので、よろしければ。
Vue Routerの導入
インストール方法
npmを使用していると、以下コマンドでインストール可能。公式ドキュメントを参考にコマンドを実行。
$ npm install vue-router
前述した環境(Laravel-mix)ではwebpackが導入されており、エントリポイントとなるapp.jsがresources/js配下に作成されていることと思います。
このapp.jsにVue Routerを定義します。
app.js
import VueRouter from "vue-router"; Vue.use(VueRouter);
ルーティングの設定
肝となる、パスに対応するコンポーネントをルーティングしていきます。
以下ドキュメントを参考に進めます。
app.js
// コンポーネントの定義
const Index = { template: "<div>index</div>" };
const Foo = { template: "<div>foo</div>" };
const Bar = { template: "<div>bar</div>" };
const NotFound = { template: "<div>NotFound</div>" };
// パスに対応するコンポーネントを定義する
const routes = [
    {path: '/', component: Index},
    {path: '/foo', component: Foo},
    {path: '/bar', component: Bar},
    {path: '/*', component: NotFound},
];
// Vue Routerのインスタンス生成。引数にルーティングを指定
const router = new VueRouter({
    routes //routes: routesの省略
});
const app = new Vue({
    router
}).$mount('#app')
コンポーネントの定義部分は今回は直接DOMを定義していますが、もちろんコンポーネントのパスをrequireして定義することも可能。
ルーティングの最後、「/*」は、それより定義していないパスにアクセスした場合に表示するコンポーネント。404エラーページ相当。
ビュー側を定義
Laravel導入時に自動生成されるwelcome.blade.phpを利用します。
「Laravel」のタイトルと各リンクの間にコンポーネントを定義(div id=”app”の要素)
welcome.blade.php
<div class="content">
    <div class="title m-b-md">
        Laravel
    </div>
    <div id="app">
        <example-component></example-component>
        <router-link to="/foo">Go to foo</router-link>
        <router-link to="/bar">Go to bar</router-link>
        <router-view></router-view>
    </div>
    <div class="links">
        <a href="https://laravel.com/docs">Docs</a>
        <a href="https://laracasts.com">Laracasts</a>
        <a href="https://laravel-news.com">News</a>
        <a href="https://blog.laravel.com">Blog</a>
        <a href="https://nova.laravel.com">Nova</a>
        <a href="https://forge.laravel.com">Forge</a>
        <a href="https://vapor.laravel.com">Vapor</a>
        <a href="https://github.com/laravel/laravel">GitHub</a>
    </div>
</div>
LaravelとVueとVue Routerによる表示を確認。

 
		  	      
      
 
		  	        
	       
			  		    	         
			  		    	         
			  		    	         
               
               
               
               
              
 
                                 
                                 
                                 
                                 
                                 
		                   
		                  ![MySQL8.xとLaravelのmigrate時にSQLSTATE[HY000] [2054] The server requested authentication method unknown to the client ・・・のエラーが出たときの対処法](https://trialanderror.jp/wp-content/uploads/2020/03/error-63628_1280-730x410.jpg) 
		                   
		                  