How to Import Component in Vuejs inside Another Component

Vue.js import one component into another component example; In this tutorial we will show you how to import a Vue.js component inside another component.

Working with long line code is irritating for developing and all are frustrate for checking code in one file, So we break the code in more then component is a better coding experience. Here if you have more then lines code in one file and want to add some code in another component and import then we use parent import child component relation with vuejs.

Import a child component in vuejs is very easy just create a child compoent and import it in parent just like below examples. Let’s check the easy example to import one component to another component steps.

Your Child Component:

Here we have created a child component just like below.

resources\js\components\ChildComponent.vue

<template>
    <div>
        <h2>This is child component.</h2>
    </div>
</template>

Import Child Compoent in Parent

Here is the parent component with impot the child class. Our child and prent class inside resources/js/component direcotory, So we import the child class look like this:

resources\js\components\ParentComponent.vue

<template>
    <div>
        <h1>This is parent component.</h1>
        <child-component/>
    </div>
</template>
<script>
    import ChildComponent from './ChildComponent.vue';

    export default {
      components: {
        ChildComponent
      }
    }
</script>

If the child component inside the folder then we add the folder name before the child complent like this:

resources\js\components\childfolder\ChildComponent.vue

Then import something like below:

<template>
    <div>
        <h1>This is parent component.</h1>
        <child-component/>
    </div>
</template>
<script>
    import ChildComponent from './child-folder/ChildComponent.vue';

    export default {
      components: {
        ChildComponent
      }
    }
</script>

So today you have learned how to import child component to parent component. I hope you enjoy to learn import one component to other component in vuejs.

Leave a Comment