How to use components in VueJS?

Hi Friends 👋,

Welcome To SortoutCode! ❤️

To use components in VueJS. we are going to declare components using the components of the vue component. Before using the props we have to import those components where we want to use the components.

What are the components of VueJS?

In vuejs, Components are the reusable Vue instances with custom HTML elements. You can define the child components and use child components in parent components as many times as you need.

Short solution

Suppose we have the child component that is ChildComp.vue and the other is the parent component that is ParentComp.vue.

`childComp.vue

<template>
    <p>Hii, This is childComp.vue</p>
</template>
<script>
export default {
  name: "childComp",
};
</script>

To use the child component into the parent component we have to fist import the component and defined the components property into Vue component.

parentComp.vue

<template>
    <ChildComp />
</template>
<script>
import ChildComp from "./components/ChildComp.vue";
export default {
  name: "parentComp",
  components: {
    ChildComp,
  },
};
</script>

Today, I am going to show you How you use components in VueJS?

Table of Content

  • Setup the Vue (Optional)
  • Creating the Child Component
  • Import child components in App.js

This article will guide you to How do I use components in vueJS.

Setup the Vue.js

First, we have to install the Vue project, I had installed the vueJS in my system. If you haven’t installed or have any problem with installation you can follow this article, it will show you step by step process of installation.

How to Install the VueJS project?

Creating the child Component

First, we are going to create the child component that is ChildComp.vue:

ChildComp.vue

<template>
  <h3>Hii, This is the ChildComp.vue</h3>
</template>
<script>
export default {
  name: "ChildComp",
};
</script>

Import child components in App.js

To use the ChildComp.vue component in App.js.First, we have to import the Child components in App.js.After that we are going to define our ChildComp.vue in components property of vue components. Let’s see the code:

App.js

<template>
  <div id="app">
    <h1>Welcome to sortoutcode.com</h1>
    <h3>This is Parent Component.</h3>
    <ChildComp />
  </div>
</template>

<script>
import ChildComp from "./components/ChildComp";
export default {
  name: "App",
  components: {
    ChildComp: ChildComp,
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

For now, let’s check the output.

Output

how to use component in vuejs

All the best 👍.

Follow me on Twitter