LoginSignup
1

More than 3 years have passed since last update.

【Vue.js】Vue-Routerを使うとURLに出てくる`#`を消す方法と注意点

Posted at

はじめに

vue-routerを使用しているとURLにデフォルトで出てくる#を消す方法についてまとめました。

公式ドキュメント

環境

OS: macOS Catalina 10.15.1
Vue: 2.6.10
vue-cli: 4.1.1
vue-router: 2.6.10

結論:ヒストリーモードにする

src/router.jsに以下を追記する。

src/router.js
const router = new VueRouter
  mode: 'history',  //追記
  routes: [
  ...
  ]
})

注意点と対処法

これで#自体は消えてくれるのですが、公式ドキュメントに注意点が書かれています。

history モードを使用する時は、URL は "普通" に見えます e.g. http://oursite.com/user/id。美しいですね!

しかしながら一点問題があります。シングルページのクライアントサイドアプリケーションなので、適切なサーバーの設定をしないと、ユーザーがブラウザで直接 http://oursite.com/user/id にアクセスした場合に 404 エラーが発生します。

※各サーバー毎の処理方法は公式に書かれているので、当記事ではnginxの設定のみ抜粋します。

nginxでの対処法

以下を記述。
これにより、もし404 Not Foundになったらindex.htmlが読み込まれます。

location / {
  try_files $uri $uri/ /index.html;
}

さらに注意点

このままでは、サーバー側が一切404 Not Foundを表示してくれなくなるので、代わりにクライアント側で表示する必要があります。

src/router.js
import NotFound from './components/NotFound.vue' //追記

const router = new VueRouter
  mode: 'history',
  routes: [
    { path: '*', //ここから3行追記
      name: 'NotFound',
      component: NotFound },
  ]
})
NotFound.vue
<template>
  <div>
    <h1>Oops!!! Page Not Found</h1>
  </div>
</template>

おわりに

最後まで読んで頂きありがとうございました:bow_tone1:

どなたかの参考になれば幸いです:relaxed:

参考にさせて頂いたサイト(いつもありがとうございます)

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
1