4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Vue Router ナビゲーションガード メモ

Posted at
  • Vue Routerのナビゲーションガード機能についてメモする。

概要

  • 画面遷移(ナビゲーション)を制御するためのフック機能を指す。
  • 以下の単位で設定できる。
    • グローバル
    • ルート
    • コンポーネント
  • 上記の場所で遷移をガードし、フックを解決しない限り遷移させないようにする。

ルートガード

  • メソッド
メソッド 実行タイミング
beforeEnter ルートの遷移前
  • router.jsに次のように記述する。
...
	routes: [
        {
          path: "/top",
          name: "top",
          // to		:次にナビゲーションされる対象の ルートオブジェクト。
          // from	:ナビゲーションされる前の現在のルート
          // next	:フックを解決するための関数
          beforeEnter: (to, from, next) => {
            
            // このタイミングで実行したい何らかの処理
            
            next();// パイプラインの次のフックに移動する。
          }
        },
...        

コンポーネントガード

  • メソッド
メソッド 実行タイミング
beforeRouteEnter コンポーネントへの遷移前(描画するルートが確立する前)
beforeRouteUpdate コンポーネントでのルート遷移(更新)前(描画するルートが変更されたとき)
beforeRouteLeave コンポーネントからの遷移前
  • 実行順:beforeRouteEnterbeforeRouteUpdatebeforeRouteLeave

  • コンポーネントに次のように記述する。

    • 記法は上述のルートガードと同じ。
export default {
	name: "testComponent",
	beforeRouteEnter (to, form, next) {
		// このタイミングで実行したい何らかの処理
		next();
	},
	beforeRouteUpdate (to, form, next) {
		// このタイミングで実行したい何らかの処理
		next();
	},
	beforeRouteLeave (to, form, next) {
		// このタイミングで実行したい何らかの処理
		next();
	}
    ...
};

グローバルガード

  • メソッド
メソッド 実行タイミング
beforeEach ルートの遷移前(コンポーネントガード解決前)
beforeResolve ルートの遷移前(コンポーネントガード解決後)
afterEach ルートの遷移後
  • インスタンスに次のように記述する。

    • 記法は、ルート、コンポーネントガードと同じ。
    export default {
    	name: "test",
    	mounted () {
    		this.$router.beforeEach((to, from, next) => {
    			// このタイミングで実行したい何らかの処理
    			next();
    		})
    		this.$router.beforeResolve((to, from, next) => {
    			// このタイミングで実行したい何らかの処理
    			next();
    		})
    		this.$router.afterEach((to, from, next) => {
    			setTimeout( () => {
    			// このタイミングで実行したい何らかの処理
                // next 関数を受け取らず、ナビゲーションに影響しない
    			}, 800);
    		})
    	}
    };
    
    • 実行順:beforeEachbeforeResolveafterEach

ナビゲーションガード実行 全体フロー

  • 大まかな実行の流れは以下となる。
    1. グローバルガードbeforeEach

    2. ルートガードbeforeEnter

    3. コンポーネントガードbeforeRouteEnter

      ※遷移元や再利用コンポーネントの有無などの条件に応じて上記以外のメソッドもトリガされることになる。より詳細は公式を参照のこと。

参考情報

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?