With Vue, you can also have a component inside the template of another Component, Let's see an example of this to understand this.

Let's say you are working on an application where you need to show a list of pending tasks on multiple places in your application.

Let's create a simple HTML page with basic elements and we will take step by step from there.

Create a Simple List of Tasks

<div class="task-list">
    <h3>List Of Tasks</h3>
    <ul>
        <li>Go to Market<li>
        <li>Pick Up Kids</li>
        <li>Bring Milk</li>
        <li>Clean Garage</li>
    </ul>
</div>

This will show a list of tasks along with the Heading.

Create a Task Component

We see that the li tag is getting repeated in the HTML, it can be handled better with the VueJS component, and also keeping the list of tasks in Vue will provide a more data-centric approach.

<div class="task-list">
    <h3>List Of Tasks</h3>
    <task v-for="task in tasks">{{task}}</task>
</div>
...
...
Vue.component('task',{
    template: `<li><slot></slot></li>`
});

let app = new Vue({
    el: '#app',
    data{
            tasks : ['Go to Market', 'Pick Up Kids', 'Bring Milk', 'Clean Garage']
        }
});

Here we have defined property named tasks in our Vue instance and have also defined a task component. Notice that we have used <slot></slot> inside our task component template. This means that whatever content is defined inside the task element will be slotted in the li tag.

This is great, but we can go a step further.

Component Within Component

Since we want the ability to put our task list on our multiple pages, wouldn't it be great if we can do it with a simple <tasks-list></tasks-list>

Let's create another component named tasks-list and move the data property inside it so that the data remains with the component instead of the root element.

   Vue.component('tasks-list', {
            template: `<div class="task-list">
                        <h3>List Of Tasks</h3>
                        <ul>
                            <task v-for="task in tasks">{{task}}</task>
                        </ul>
                       </div>`,
            data(){
                return{
                    tasks : ['Go to Market', 'Pick Up Kids', 'Bring Milk', 'Clean Garage']
                }
            }
    });

Here we have used the task component directly inside our tasks-list component. And to print, the list of tasks along with the heading all you have do is just use the following element on your page.

<task-list></task-list>

This should result in the following output.

component within components VueJS

That's all about having Components within Component.

Comments