Vue3/코딩애플 part2
[Vue/코딩애플/part2] 5. Nested routes & push 함수
김나나_
2024. 8. 1. 18:42
📌 Nested routes
특정 페이지 안에서 route 를 나누고 싶을 땐 nested route 를 쓴다.
/detail/0/author 로 접속하면 작가 소개 페이지로 이동시켜주고 싶다면?
/detail/0/comment 로 접속하면 댓글 페이지로 이동시켜주고 싶다면?
detail 페이지 안에서 또 페이지를 쪼개는 것을 Nested routes 라고 한다.
컴포넌트를 숨겼다가 보여 주는 식으로 만들어도 되지만,
다른 URL 로 나누고 싶다면 nested routes 를 쓴다.
children : [
{
path: "경로",
component: "컴포넌트"
},
{
path: "경로",
component: "컴포넌트"
},
]
import { createWebHistory, createRouter } from "vue-router"; // vue-router 라이브러리를 import 한다
import List from "@/components/List.vue";
import Home from "@/components/Home.vue";
import Detail from "@/components/Detail.vue";
import NotFound from "@/components/NotFound.vue";
const routes = [
{
path: "/",
component: Home
},
{
path: "/list",
component: List,
},
{
path: "/detail/:id(\\d+)",
component: Detail,
children: [
{
path: "author", // 슬래시 붙이지 않음
component: Author컴포넌트,
},
{
path: "comment",
component: comment컴포넌트,
}
]
},
// 위 path 를 제외한 path 로 접근 시 404 페이지 노출
{
path: "/:anything(.*)", // 아무 문자 입력 가능, 엄격하게 검사하고 싶으면(.*) 추가
component: NotFound, // 404 페이지 컴포넌트
}
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
🔎 tip ) 라우터 관련 에러는 콘솔창에서 볼 수 있다.
⚡ children 의 path 에는 /(슬래시) 를 붙이지 앟는다. /author (X) author (O)
childern 의 상위 컴포넌트 (예시에서는 Detail.vue) 에 <router-view> 를 추가해주면 그 차리에 nested route 의 컴포넌트가 노출된다.
// Detail.vue
<template>
<div class="container-fluid">
<h2 class="mt-4">{{ list[$route.params.id].title }}</h2>
<p class="mt-4">{{ list[$route.params.id].content }}</p>
</div>
<router-view></router-view>
</template>
// Commnet.vue
<template>
<div>
댓글 입니다.
</div>
</template>
<script>
export default {
name : 'Comment',
}
</script>
<style>
</style>
📌 Push 함수
클릭 했을 때 router 를 이동시키고 싶다면 <router-link> 를 활용해도 되지만
@click="$router.push('이동 시킬 링크')
를 활용 할 수 있다.
아래와 같은 형식으로 쓰면 된다.
<div @click="$router.push(`/detail/${i}`)" class="card shadow-sm">클릭할 영역 </div>
⚡ 헷갈리지 말기
$route 는 현재 경로에 대한 정보
$router 는 페이지 이동 관련 기능 / ex) $router.go(-1)
한 라우터 안에 여러 개 컴포넌트를 보여주고 싶을 때는
named views 를 활용 한다
필요할 때 검색해서 적용해보기
그 외
redirection 등의 기능도 있다.