Global Before Guardsにさわる

ログインしてない状態で、ログインが必要なページが要求された場合にログイン画面へリダイレクトさせたい。

Vue RouterのGlobal Before Guardsという仕組みで実現できるようなのでやってみた。

Navigation Guards | Vue Router

src/router/index.ts

import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import { store } from "@/store/AuthStore";

/*
 * ログインが必要なページのmeta情報に「requiresAuth: true」を設定
 */
const routes: Array<RouteRecordRaw> = [
  {
    path: "/login",
    name: "LoginPage",
    component: () => import("@/views/login/LoginPage.vue"),
  },
  {
    path: "/",
    name: "HomePage",
    component: () => import("@/views/menu/HomePage.vue"),
    meta: { requiresAuth: true },
  },
  {
    path: "/sample-store",
    name: "StoreSamplePage",
    component: () => import("@/views/sample/StoreSamplePage.vue"),
    meta: { requiresAuth: true },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

/*
 * to: Route: 次にナビゲーションされる対象のルート
 * from: Route: ナビゲーションされる前の現在のルート
 * next: Function: フックを解決するための関数
 */
router.beforeEach((to, from, next) => {
  if (
    to.matched.some((record) => record.meta.requiresAuth) &&
    !store.getters.isLoggedIn
  ) {
    // ログインが必要(requiresAuth === true)かつ未ログインの場合、ログイン画面へ遷移
    next({ path: "/login", query: { redirect: to.fullPath } });
  } else {
    // 要求されたページへ遷移
    next();
  }
});

export default router;