๐ Language/Vue
[Vue] ๋ผ์ฐํฐ(Router) ๋ฐฉ์ (Nested Routers, Named Views)
a n u e
2022. 5. 4. 16:47
1. Nested Routers
๋ผ์ฐํฐ ์ปดํฌ๋ํธ ์์ ํ์ ์ปดํฌ๋ํธ๋ฅผ ์ค์ฒฉํ์ฌ ๊ตฌ์ฑ
ํน์ URL์ ์ง์ ๋ ํ๋์ ์ปดํฌ๋ํธ๊ฐ ์ฌ๋ฌ ๊ฐ์ ํ์ ์ปดํฌ๋ํธ๋ฅผ ๊ฐ์ง
children ์ต์ ์ฌ์ฉ
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<template>
<div id="app">
<!-- URL์ด /user์ธ ๊ฒฝ์ฐ, User๋ผ๋ ์ด๋ฆ์ component๊ฐ ๋ค์ด์ด -->
<router-view></router-view>
</div>
</template>
<script>
const User = {
template: `<div class="user">
<h2>User {{ $route.params.id }}</h2>
// id๊ฐ์ ๋ง๋ User์ ํ์ ์ปดํฌ๋ํธ๊ฐ ๋ค์ด์ด
<router-view></router-view>
</div>`,
}
const routes = [
{
path: '/user/:id',
component: User,
children: [{
// /user/:id/profile
path: 'profile',
component: UserProfile,
},
{
// /user/:id/posts
path: 'posts',
component: UserPosts,
},
],
},
]
</script>
</body>
</html>
2. Named Views
ํน์ URL์ ๊ฐ์ ๋ ๋ฒจ์ ๋ค์์ ์ปดํฌ๋ํธ๋ฅผ '์์ญ๋ณ'๋ก ์ง์ ํ์ฌ ๋ ๋๋ง
components ์ต์ ์ฌ์ฉ
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<template>
<div id="app">
<router-view name="appHeader"></router-view>
<router-view></router-view>
<router-view name="appFooter"></router-view>
</div>
</template>
<script>
const routes = [{
path: '/home',
components: {
appHeader: AppHeader,
default: Body,
appFooter: AppFooter
}
}]
</script>
</body>
</html>
ํ์ฌ ์ค๋ฌด์์๋ ๊ธฐ๋ณธ ๋ผ์ฐํฐ ํ์์ด๋, 1๋ฒ ํ์์ด ์ข ์ข ๋ณด์ด๋ ๋ฏ ํ๋ค.
์ฐธ๊ณ
router-link์ path๋ง๊ณ , name๊ฐ์ ์ ์ด์ค ์๋ ์๋ค.
๊ทธ๋ผ name์ด๋ ๋งคํ๋๊ฒ ์ง .. ?
<router-link :to="{ name: 'user', params: { username: 'kimeuna' }}">User</router-link>
const routes = [
{
path: '/user/:username',
name: 'user',
component: User
}
]