๐Ÿ“• 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
  }
]