Vue.js Import A Component

Vue.js

When an app gets bigger, we’ll need to split the code into child components for reusability purposes.

Let’s see how to import a Child Component to a Parent Component with 3 simple steps.

Let’s say you have a folder structure like this:

/src
  /pages (parent)
    ContactsApp.vue
  /components (child)
    AddContactForm.vue
    ShowContactsList.vue

STEP 01: First, Import the Child Component into the Parent Component inside script tag but above export default function declaration.

ContactsApp.vue

import AddContactForm from '@/components/AddContactForm';

STEP 02: Then, Register the Child Component inside the Parent Component by adding it to components object.

ContactsApp.vue

components: {
  AddContactForm
}

STEP 03: Finally, Use the Child Component in the Parent Component Template.

If you’re using Options API, you need to have a top-level HTML element and others will be under it.

ContactsApp.vue

<AddContactForm />

Similar way, the child component can be imported multiple parent components or other child components depending on the app.