5
6

More than 3 years have passed since last update.

Vue beforeEnter でルート単位のナビゲーションガード

Posted at

はじめに

vueのナビゲーションガードのbeforeEnterについて説明や使い所を記載しています。
実際の案件で使って頭を悩ませたので誰かの役に立てば嬉しいです☺️

beforeEnterとは

beforeEnterとはVueのナビゲーションガード(画面遷移ガード)の一つです。beforeEnter意外にもbeforeEach,
beforeRouteEnterなどガードのパターンはありますがbeforeEnterルート単位でガードをかけられるという特徴を持っています。

ルート単位でナビゲーションガードをかけられるメリット

実際にどのような記述をするか見てみましょう。

src/router/index.js
const routes = [
  {
    path: '/test',
    name: Test,
    component: Test,
    beforeEnter: (to, from, next) => {
      // ここに処理を記載します
      next(); // ガードを通過しページ遷移する場合はnext()を使用します
    }
  },
  {
    path: '/error',
    name: Error,
    component: Error,
    // こちらのルートには記載しない
  }
]

このようにrouterに記述された各ルートに対して個別で処理を記載できます。
そのため特定のページにのみ遷移前にバリデーションをかけたい場合に活用できます。
以下のようなイメージです。

src/router/index.js
const routes = [
  {
    path: '/test',
    name: Test,
    component: Test,
    beforeEnter: (to, from, next) => {
      function validation() {
        if (to.params.id === 1) return true;
        return false;
      }
      if (validation()) {
        next(); // 正常に遷移
      } else {
        next({ path: 'notfound' }); // next()はpath等指定しそちらに飛ばすことも可能
      }
    }
  }
]

ただロジックをrouterに書きまくることで、みづらくなる感は否めません、、
とはいえ、次ページに遷移前にはじけるため重宝しております。

注意点

next()を忘れるとナビゲーションガードされたままで画面遷移が起きないため、beforeEnterを使うばあい必ずnext()を記載しましょう!

5
6
1

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