0
0

More than 1 year has passed since last update.

vue3 beforeEach で ログイン管理

Posted at

・外部から直接URLを指定してもmypageで弾く
・mypageに行く前にlocalStorage があるかチェック

?crypt_id がある場合は localStorageにデータを入れる
ない場合はログインしてねページへ飛ばす

app.js

    const routes = [
        {
            path: "/mypage",
            component: Mypage,
            meta: { requiresAuth: true,title: 'マイページ' }
        },
    ];


    //router
    const router = createRouter({
        routes, // short for `routes: routes`
        history: createWebHistory(),
        scrollBehavior
    })


    //beforeEach
    router.beforeEach((to, from, next) => {

        //?crypt_id があれば storageに セット
        if(to.query.crypt_id){
            localStorage.setItem('crypt_id',to.query.crypt_id);
        }

        if (to.matched.some(record => record.meta.requiresAuth)) {
            if(localStorage.getItem('crypt_id')){
                next();
            } else {
                next({ path: '/login', query: { redirect: to.fullPath }});
            }

        } else {
            next();
        }

    });



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