LoginSignup
0
1

More than 3 years have passed since last update.

【Vue.js】Vue Routerのナビゲーションガードでリダイレクトの設定

Posted at

Vue Routerのナビゲーションガードでリダイレクトの設定

投げ銭アプリを作成中。
ログインしていないユーザーはログイン画面にリダイレクトされるようにしたい

公式

router.beforeEach

ルーターインスタンスのメソッドで、画面遷移前に実行される処理を引数に記載

遷移先をnext()で指定

router.beforeResolve

主にガードする場所は以下の4箇所
1. グローバルbeforeEach
2. ルート単位beforeEnter
3. コンポーネント単位beforeRouteEnter
4. コンポーネント単位beforeRouteUpdate

実際設定したコードは以下


router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  // ルートメタフィールドのrequiredAuthプロパティがtrueの場合、認証されているかどうかをチェックする挙動を実装
  if (requiresAuth) { //true or false
    firebase.auth().onAuthStateChanged(function (user) { // ログインしているユーザーを取得(ユーザの有無)
      // ログインされているかどうか認証
      if (user) {
        next() //nextを呼ぶとtoのコンポーネントに遷移
      // ログインページにリダイレクト
      } else {
        next({
          path: '/signin',
          query: { redirect: to.fullPath }
        })
      }
    })
  // メタフィールドがture出なければダッシュボードに遷移してしまう
  } else {
    next()
  }
})


参考

ルートメタフィールドのrequiredAuthプロパティがtrueの場合、認証されているかどうかをチェックする挙動を実装する。

0
1
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
0
1