Laravel + vue-router vue SPAページのRouting @vueJS inside Laravel

基本

app.jsで記述したpathをlaravel側のweb.phpにも記述。その際、returnするviewはvueの起点ページにする。

Route::get('/profile', function() {
  return view('home');
});

→ home.blade.phpにvue componentのprofileがある場合、profileがレンダリングされた状態で開ける。

ただしcomponentがnestされている場合...

@app.js

const routes = [
  { path: '/profile', component: Profile,
    children: [
      {
        path: '/follow', component: Follows,   ・・・
      },
      {
        path: 'activity', component: Activity  ・・・
      }
    ]
  },

 

@web.php

Route::get('/follow', function() {   ・・・
  return view('home');
});

Route::get('/profile/activity', function() {  ・・・
  return view('home');
});

 

@親component

<router-link to="/follow">Following</router-link>   ・・・

<router-link to="/profile/activity">Activity</router-link>  ・・・

 

activityはprofileページからrouter-linkを通した場合開けるが、ページリロードの場合、component profile, activityともにレンダリングされない。

/profile/activityがrouter-viewに反映されない。

一方、child componentのfollowはpathを/followとし、root path化するとリロード経由でもレンダリングされる。

 

child componentをリロード経由で表示させたいならpathをrootにする(pathをnestできない???純粋なVue SPAならこの制約外。)

 

nestされたpathのrest化に成功

  • 問題点だったもの

vue関連を含むapp.jsの読み込み方法に問題があった

app.blade.php内にて下記のように記述

<script src='js/app.js'></script>…×

相対path表記だったため、例えば/profile/activityをロードするとapp.jsがprofile/js/app.jsになりnot foundになる。

こちらに訂正⇒ <script src="{{ asset('js/app.js') }}"></script>…〇

絶対path表記に変更

 

 new issue:

laravel側のparameter付きroute と vue側のrouteがぶつかる

VM314:65702 Uncaught TypeError: Cannot redefine property: $router 

 

layoutを設定したapp.blade.php内で読み込んだjavascriptファイル内にajaxリクエストをするscriptがあり、この影響でparameter付きroute時にエラーが発生していた。

error: [Deprecation] Synchronous

XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/. 

error: Uncaught TypeError: Cannot redefine property: $router

具体的には以下をコメントアウトしてエラーが除けた

app.blade.php内(layoutを設定していたファイル)

$.get("skin-config.html", function (data) {
  if (!$('body').hasClass('no-skin-config'))
  $('body').append(data);
});

参考:

laracasts.com

SPA with Vue.js and Laravel: Routing Basics

mattstauffer.co

SPA with Vue.js and Laravel: Routing Basics

 

  • router-linkにparameterとさらにもう一層nestされたroute

<router-link :to="{ path: '/user/' + user.name + '/follow' }" >

<router-link :to="{ path: '/user/' + user.name + '/activity' }" >

computed: {
  user() {
    return this.$store.state.user.user;  /* define param */
  }
},

@app.js

const routes = [

  {   path: '/user/:userName', name: 'user', component: Profile,
    children: [
      {
        path: '', component: Activity  /* /user/param */
      },
      {
        path: 'follow', component: Follows    /* /user/param/follow */
      },
      {
        path: 'activity', component: Activity    /* /user/param/activity */
      }
  ]
},