LoginSignup
6
7

More than 5 years have passed since last update.

Laravel + vue-routerでハッシュ記号(シャープ記号)をなくしてちゃんと動くようにする方法

Last updated at Posted at 2018-10-07

ハッシュ記号をなくす方法

vue-routerはデフォルトでは、ルーティングに「#」記号がつくようになっています。
これを消す方法として公式が紹介しているのは、インスタンスを作るとき

  const router = new VueRouter({
    mode:'history',
    routes:[
        { path: '/foo', component: Foo },
        { path: '/bar', component: Bar }
    ]
  })

のように、mode:'history'にしろ、とのこと。

でも動かない

それをやってもなぜか私の環境では動きませんでした。
環境は以下の通り
・windows10
・Xampp
・Laravel 5.7
・vue-router
・vue

いずれも2018年10月現在最新版を使用しています。
WindowsのXampp環境ではしばしばルーティングに問題が起きるようです。

解決方法?

ネットで調べる限り、Laravel側の問題として紹介されることが多いようです。
おおむねLaravelのルート設定を変える方法が出てきましたが、私の環境ではうまく解決できませんでした。

Route::get('/{vue?}', function () {
    return view('index');
 })->where('vue', '[\/\w\.-]*');

解決できた方法

問題はベースとするURLがうまく設定されていなかったことでした。
これはインスタンス・オプションの一つであるbaseオプションを変えればいいようです。
仮にLaravelでappというディレクトリをルートとしていると、以下の通り

  const router = new VueRouter({
    mode:'history',
    base:'/app/public/',
    routes:[
        { path: '/foo', component: Foo },
        { path: '/bar', component: Bar }
    ]
  })

感想

とりあえずこの辺りでコケてしまっているLaravel + vue + vue-routerユーザーの皆様の問題解決に役立てれば幸いです。

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