Episode 19 of 44

Nesting Components

Import and nest child components inside parent components — build a component tree from reusable pieces.

Nesting Components

Real applications are composed of many components nested inside each other. In this episode you will learn how to import child components and use them inside a parent component.

Creating a Child Component

<!-- src/components/Ninjas.vue -->
<template>
    <div>
        <ul>
            <li v-for="ninja in ninjas" :key="ninja.name">{{ ninja.name }} - {{ ninja.rank }}</li>
        </ul>
    </div>
</template>

<script>
export default {
    name: 'Ninjas',
    data() {
        return {
            ninjas: [
                { name: 'Ryu', rank: 5 },
                { name: 'Ken', rank: 3 },
                { name: 'Yoshi', rank: 8 }
            ]
        };
    }
};
</script>

Using the Child in the Parent

<!-- src/App.vue -->
<template>
    <div id="app">
        <h1>{{ title }}</h1>
        <Ninjas />
    </div>
</template>

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

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

Steps to Nest a Component

StepCode
1. Importimport Ninjas from './components/Ninjas.vue'
2. Registercomponents: { Ninjas }
3. Use in template<Ninjas />

Key Takeaways

  • Import child components with import, register them in components, then use as tags
  • Each component has its own isolated data and methods
  • Components can be nested to any depth — building a component tree