Vue - Router 두 번째

h.Im·2024년 9월 12일

Vue 기초

목록 보기
13/28
post-thumbnail

이전 Router 벨로그에 이어서 라우터에 대해 좀 더 공부해 보겠습니다.

...

const routes = [
	{
		path: '/',
		name: 'Home',
		component: HomeView,
	},
	{
		path: '/posts/create',
		component: PostCreateView,
	},
	{
		path: '/posts/:id',
		component: PostDetailView,
	},
	{
		path: '/posts/:id/edit',
		component: PostEditView,
	},
]

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

export default router

라우터의 path를 /posts/:id 와 같이 지정함으로써, 파라미터를 받는 구조를 만들 수 있습니다. 이런 라우팅을 동적 라우팅이라고 표현합니다. pathVariable은 위처럼 지정하고, query 데이터나 hash는 컴포넌트 내부에서 따로 접근하여 사용합니다(라우터에 드러나지는 않음).


router.push로 페이지 이동

router.push로 페이지 이동할 때 여러 가지 방식이 있습니다.

문자열로 이동하기

this.$router.push('/home');

경로 객체로 이동하기

this.$router.push({ path: '/about' });

이름으로 이동하기

위 코드는 name: 'user'인 라우트로 이동하며, 경로는 예를 들어 /user/123이 될 수 있습니다.

this.$router.push({ name: 'Home', params: { id: 123 } });

이름으로 이동하는 경우는 라우터에 이름이 지정된 경우 사용할 수 있습니다(상단 예시에서, HomeView로 이동하는 라우터의 이름을 Home으로 지정함).

쿼리와 함께 이동하기

쿼리 파라미터는 URL에 ? 뒤에 추가되며, 이를 통해 특정 데이터와 함께 라우팅할 수 있습니다.

this.$router.push({ path: '/search', query: { q: 'vue' } });

해시와 함께 이동하기

위 코드는 /about#team 경로로 이동합니다. 해시는 보통 페이지 내 특정 섹션으로 이동할 때 사용됩니다.

this.$router.push({ path: '/about', hash: '#team' });

404 not found 페이지 만들기

Catch-all Route

정규식 패턴을 사용하여 모든 일치하지 않는 경로를 잡아 404 페이지로 리다이렉트하는 방식입니다. 이 패턴은 Vue Router 4.x 버전부터 권장하는 방법으로, 모든 경로를 잡아줍니다.

...

const routes = [
	...
	{
		path: '/:pathMatch(.*)*',
		name: 'NotFound',
		component: NotFoundView,
	},
]

...

중첩 라우트 적용

라우터 설정

중첩 라우팅은 부모 라우트 아래에 children 속성을 사용하여 하위 라우트를 정의할 수 있습니다.

import { createRouter, createWebHistory } from 'vue-router';
import UserView from '@/views/UserView.vue';
import UserProfile from '@/views/UserProfile.vue';
import UserSettings from '@/views/UserSettings.vue';

const routes = [
  {
    path: '/user/:id',
    component: UserView, // 부모 컴포넌트
    children: [
      {
        path: 'profile', // /user/:id/profile
        component: UserProfile,
      },
      {
        path: 'settings', // /user/:id/settings
        component: UserSettings,
      }
    ]
  }
];

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

export default router;

children의 path에는 /가 들어가지 않는 점은 기억해 두어야 할 것 같습니다.

부모 컴포넌트 설정

부모 컴포넌트에서 자식 라우트를 렌더링할 수 있도록 router-view를 넣어야 합니다. 이 router-view는 자식 컴포넌트가 렌더링될 영역입니다.

<!-- UserView.vue -->
<template>
  <div>
    <h1>User {{ $route.params.id }}</h1>
    <router-link to="profile">Profile</router-link>
    <router-link to="settings">Settings</router-link>
    
    <!-- 자식 라우트가 여기에 렌더링 -->
    <router-view></router-view>
  </div>
</template>

주의할 점은, 중첩 라우팅으로 인해 화면의 일부가 변할 때, 히스토리가 축적되는 점입니다. 아래 router.replace 등을 적절히 활용하여 요건에 맞는 히스토리 조작히 필요해 보입니다.

router.replace

<RouterLink
	class="nav-link"
	active-class="active"
	:to="{ name: 'NestedTwo', replace: true }">
    Nested Two
</RouterLink>

router.replace는 히스토리를 축적하지 않고 이동하는 기능입니다.

0개의 댓글