LoginSignup
0
0

More than 1 year has passed since last update.

Vue Routerでログインしていないユーザーをログイン画面に遷移させる

Posted at

やりたこと

ログインを必要なページにログインしていないユーザーがアクセスした際にログイン画面に遷移させたい。

実現方法

Vue Routeでは、各ルートごとに任意の情報をmetaプロパティに設定できる。
ログイン必要有無(requiresAuth)を持たせて、ログインが必要なページにログインしていないユーザがアクセスした際は、beforeEachの処理でログイン画面に遷移させる。

import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'
import TodoListView from '../views/TodoListView.vue'
import { authStore } from '../stores/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: { requiresAuth: false }
    },
    {
      path: '/todos',
      name: 'todolist',
      component: TodoListView,
      meta: { requiresAuth: true }
    },
  ]
})

router.beforeEach((to, from) => {
  const auth = authStore()
  if (to.meta.requiresAuth && !auth.isLogin) {
    return {
      path: '/login',
      query: { redirect: to.fullPath },
    }
  }
})

export default router

公式ドキュメント

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