2
1

More than 3 years have passed since last update.

ナビゲーションガードを利用して未ログインのアクセスを不可にする

Posted at

概要

特定のURLにログインしていないユーザーが入れないようにするためにフロント側で制御できないか模索していたら、ナビゲーションガードという機能がVue-routerに存在することを知ったので備忘録としてメモします。

ナビゲーションガードとは

公式

ルーティングが行われる前にバリデーションをすることで、アクセスを制御できる機能

ナビゲーションガードは何種類か用意されており、用途によって使い分けることができます。
大きく2つに分かれており、1.全てのルーティングに対して行われる処理2.特定のルーティングに対して行われる処理です。
今回は、1.全てのルーティングに対して行われる処理を利用していきたいと思います。

処理内容

未ログインのユーザーは全てのページに対して/loginにリダイレクトする処理にします。
全てのルーティングに対して行う場合は、beforeEachを使います。
ルーティングが呼び出されるたびに、毎回beforeEachの中に書かれた処理を行ってくれます。

router.js
import Vue from "vue";
import VueRouter from "vue-router";
import store from './store'; //ストア

Vue.use(VueRouter);

const router = new VueRouter({
    mode: 'history',
    routes:[
        {
            path: '/',
            name: 'home',
            component: HomeComponent,
        },
        {
            path: '/photo/:postId',
            name: 'individual',
            component: Individual,
        },
        {
            path: '/login',
            name: 'login',
            component: Login,
        },
    ]
})

router.beforeEach((to,from,next)=>{
    if(!store.getters["auth/check"]){  //ログイン済み:true,未ログイン:false
        next('/login')  // /loginにリダイレクトされる
    }else{
        next()
    }
})

export default router;

参考文献

Vue beforeEnter でルート単位のナビゲーションガード
Vue-Routerのナビゲーションガードを使ってみる

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