Episode 21 of 44

Nesting Components Examples

Practice nesting components with real-world examples — build a header, footer, and content components to compose a complete page layout.

Nesting Components Examples

Let us build a practical layout using nested components — a header, a main content area with a ninja list, and a footer. This mirrors how real Vue applications are structured.

Component Tree

App.vue
├── Header.vue
├── Ninjas.vue
│   └── NinjaCard.vue (for each ninja)
└── Footer.vue

Header Component

<template>
    <header>
        <h1>{{ title }}</h1>
        <nav>
            <a href="#">Home</a>
            <a href="#">About</a>
        </nav>
    </header>
</template>

<script>
export default {
    name: 'Header',
    data() {
        return { title: 'Ninja Directory' };
    }
};
</script>

<style scoped>
header { display: flex; justify-content: space-between; padding: 20px; background: #333; color: #fff; }
nav a { color: #42b883; margin-left: 16px; text-decoration: none; }
</style>

Footer Component

<template>
    <footer>
        <p>Copyright {{ year }} Ninja Directory</p>
    </footer>
</template>

<script>
export default {
    name: 'Footer',
    data() {
        return { year: new Date().getFullYear() };
    }
};
</script>

<style scoped>
footer { text-align: center; padding: 20px; background: #222; color: #999; }
</style>

Composing in App.vue

<template>
    <div id="app">
        <app-header></app-header>
        <ninjas></ninjas>
        <app-footer></app-footer>
    </div>
</template>

<script>
import Header from './components/Header.vue';
import Ninjas from './components/Ninjas.vue';
import Footer from './components/Footer.vue';

export default {
    name: 'App',
    components: {
        'app-header': Header,
        'app-footer': Footer,
        Ninjas
    }
};
</script>

Note: Header and Footer conflict with native HTML element names, so we register them as app-header and app-footer.

Key Takeaways

  • Break your app into logical components: Header, Content, Footer, Cards, etc.
  • Each component manages its own data, template, and scoped styles
  • Rename components that conflict with HTML element names (Header → app-header)
  • The component tree reflects the visual hierarchy of your app