Creating a Child Component

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $12.00

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

The products.vue file is known as a component. And, as we can see, a component represents a set of HTML, complete with CSS for that HTML and even behavior for those elements, which we'll learn about soon.

In the same way that HTML elements can be placed inside of each other, Vue components can also be nested inside of each other. For example, we could move an entire section of HTML into another .vue file and then include that component in the same spot.

And... this is often a great idea! Because, if we built our entire app in this one file, it would become huge and complex!

When & Why to Extract to a Component

We have this same problem in PHP: if you have a large or complex function, you might decide to extract part of it into a different function. You might do this because you want to re-use the extracted code or just because separating things keeps your code more readable and better organized.

As a general rule, if an area of your DOM has (1) special functionality, (2) needs to be reused or (3) would just make the original template easier to read, you should consider extracting it into its own component.

Creating the Second Component

It's not really very complex, but let's pretend that we want to reuse the "legend" functionality in other places and pass different text each time we use it.

Let's go! Inside the js/ directory, create a new sub-directory called components/. I'm not going to put this new component in pages/: pages/ is sort of meant to hold "top-level" components, while components/ will hold everything else: Vue components that contain little bits and pieces of HTML and that, in theory, could be re-used.

Inside components/, create a new file called legend.vue. Start the exact same way as before: add <template> and, inside, copy the <span> from products.vue and paste. To keep things simple, I'm going to temporarily copy the old shipping message and hardcode it: the component will start off completely static.

<template>
<span class="p-3">
Shipping takes 10-12 weeks, and products probably won't work
</span>
</template>
... lines 6 - 12

The other tag we need is <script> with export default {}. The only option that we should always have is name. Set it to Legend.

... lines 1 - 6
<script>
export default {
name: 'Legend',
};
</script>

Rendering a Component inside a Template

Component... done! Using this in the Products component is a three step process. First: inside the <script> tag - just like we normally do in JavaScript - import it: import LegendComponent... - we could call that anything - from '../components/legend'.

... lines 1 - 55
<script>
import LegendComponent from '../components/legend';
... lines 58 - 69
</script>
... lines 71 - 85

Second, to make this available inside the template, add a new option called components. As I've mentioned, there are a number of options that you can add here to configure Vue, like name, data() and components. There aren't a tons of them - so don't worry - and we'll learn the most important ones little-by-little.

... lines 1 - 58
export default {
... line 60
components: {
LegendComponent,
},
... lines 64 - 68
};
... lines 70 - 85

If we stopped now, nothing would change: this makes LegendComponent available to our template, but we're not using it. In fact, that's why ESLint is so mad at me:

The "LegendComponent" has been registered but not used.

The last step is to go to our template, remove the old code, and use the LegendComponent as if it were an HTML tag. Type <. You might be expecting me to say <LegendComponent/>... after all, PhpStorm is recommending that. Instead, use the kebab-case option: <legend-component />.

<template>
... lines 2 - 47
<div class="row">
<legend-component />
</div>
... lines 51 - 53
</template>
... lines 55 - 85

Using LegendComponent would have worked, but when we add a key to components, like LegendComponent, Vue also makes it available in its kebab-case version: so legend-component. It does that so our template can look cool by using the HTML standard of lowercase and dashes everywhere.

Anyways, let's try it! Move over, refresh and... it works! But the real prize is over on the Vue dev tools. Nice! Our component hierarchy is growing! We now have a <Legend> component inside of <Products>.

Of course... its text is now static... so we also kinda took a step backwards. Next, let's learn how to pass info from one component into another with props.

Leave a comment!

  • 2020-06-30 Victor Bocharsky

    Hey Alexei,

    We're sorry to hear you have some troubles with running this example! Do previous examples work for you (examples in previous chapters)? Could you give us a little bit more context? What exactly are you doing? Do you see any errors in Console tab of Google Chrome? We will be happy to assist you if we know a little more about your problem.

    Cheers!

  • 2020-06-29 Alexei Saron

    don't work this example

  • 2020-06-12 Matias Jose

    No problem! Looking back at the issue, I know what the problem was: When you do it the first way, you're only passing data and the render function to the Vue engine, not the entire App object. Thus, once you start adding properties to App, those get lost in the way, therefore, you need to change the syntax and just give Vue the entire thing!

  • 2020-06-11 trrtr

    Passing App to createApp worked! Thank you for your help :)

  • 2020-06-10 Matias Jose

    Hi trrtr!

    I'm not sure why would you get such an error in Vue 3. Does it work with Vue 2?

    I'd try to instantiate my App as follows:


    createApp(App).mount('#app');

    And see if that makes it recognize App's child components!

  • 2020-06-09 trrtr

    What does it mean to define it before main instance? Should I add something to products.js?
    Now it looks like this:


    import { createApp } from 'vue';
    import App from './pages/products';


    createApp({
    data: App.data,
    render: App.render,
    }).mount('#app');

    My products.vue (without template), in which I call <legend-component/>:


    <script>
    import LegendComponent from '../components/legend';

    export default {
    name: 'Products',
    components: { LegendComponent },
    data() {
    return {
    legend: 'Shipping takes 10-12 weeks, and products probably won\'t work',
    };
    },
    };
    </script>

    And a legend.vue:


    <template>

    Shipping takes 10-12 weeks, and products probably won't work

    </template>


    <script>
    export default {
    name: 'LegendComponent',
    };
    </script>

    Everything from products.vue renders correctly except legend-component :(

  • 2020-06-09 Victor Bocharsky

    Hey Trrtr,

    Hm, my guess is that you need to define your "legend-component" component before you initiate your main instance.

    I hope this helps!

    Cheers!

  • 2020-06-06 trrtr

    Hi, after creating Legend component I'm getting:

    [Vue warn]: Failed to resolve component: legend-component at <app>

    Is this issue with vue 3 or am I doing something wrong?