기본 콘텐츠로 건너뛰기

router/index.js 관련 내용. createRouter, beforeEach, afterEach - vuejs 관련

router 관련 세팅


/router/index.js or router.js

import { createRouter, createWebHistory } from "vue-router"

// const alwaysTitle = "브라우저 틀에 항상 보여지는 타이틀"

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  
  // 라우터 이동 시 이전 화면으로 돌아갈 때 이전 스크롤 위치로 이동할 경우 확인(savedPosition)
  scrollBehavior(to, from, savedPosition) {
    console.log('SavedPosition', savedPosition)
    if (savedPosition) {
      return savedPosition
    }
    return { top: 0, left: 0 }
  },
  
  routes: [
    // { path: "/", redirect: "/directurl" },
    {
      path: "/404",
      name: "notFound",
      component: () => import("@/views/NotFound.vue"),
      meta: {
        title: "페이지를 찾을 수 없습니다"
      }
    },
    { path: "/:pathMatch(.*)*", redirect: "/404" },
    
    // 로그인 레이아웃
    {
      path: "/login",
      name: "loginLayout",
      component: () => import("@/components/layout/LoginLayout.vue"),
      children: [
        // 로그인
        {
          path: "",
          name: "login",
          component: () => import("@/views/login/Login.vue"),
          meta: {
            title: alwaysTitle + " - Login"
          }
        },
        // 아이디 찾기, 비밀번호 찾기
        {
          path: "/findidpw/:no",
          name: "findidpw",
          component: () => import("@/views/login/Findidpw.vue"),
          props: true,
          meta: {
            title: alwaysTitle + " - 아이디/비밀번호 찾기"
          }
        },
        // ......
        // ...
      ]
    },
    
    // 기본 레이아웃
    {
      path: "/",
      name: "defaultLayout",
      component: () => import("@/components/layout/DefaultLayout.vue"),
      meta: {
        requiresAuth: true
      },
      children: [
        // 목록 등
        {
          path: "/list",
          name: "list",
          component: () => import("@/views/member/List.vue"),
          meta: {
            title: alwaysTitle + " - 목록"
          }
        },
        // ......
        // ...
      ]
    },
    
    // 팝업 레이아웃 등
    // ......
    // ...
  ]
})

// 라우터 이동 전
router.beforeEach((to, from) => {
  document.title = to.meta.title
  
  // 라우터 이동 시 scrollTo(0, 0) 일 때 맨위로 바로 이동되게 하려고(부드러운 이동 X)
  // document.documentElement.classList.add("scrollbehavior_no");
  
  if(to.meta.requiresAuth 
     && !(JSON.parse(localStorage.getItem('loginInfo'))?.isLogin
     || JSON.parse(sessionStorage.getItem('loginInfo'))?.isLogin)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    return {
      path: "/login",
      // save the location we were at to come back later
      query: { redirect: to.fullPath }
    }
  }
})

// 라우터 이동 후
router.afterEach((to, from) => {
  // setTimeout(() => {
    // 라우터 이동 시 scrollTo(0, 0) 일 때 맨위로 바로 이동되면 다시 부드러운 스크롤 이동이 시작
    // document.documentElement.classList.remove("scrollbehavior_no");
  // }, 600);
})

export default router

라우터 구조 예시


끝.