Author: Dawid Adach
Amongst other advantages, Vue gained incredible momentum within the last year thanks to its reactive and composable components. Components are reusable Vue instances with a name. We can use this component as a custom element inside a root.
It’s common for an app to be organized into a tree of nested components:

In this lesson, we will learn how to create, use and organize components.
1. Create and export component
- Create a new folder and call it
components
inside thesrc
folder: - Create a new file called
HelloWorld.vue
insidecomopnents/
folder: - Open the
HelloWorld.vue
file and paste the following code into it:


<template>
<div class="hello">
<h3>I am Hello World Component</h3>
</div>
</template>
<script>
export default {
name: "HelloWorld"
};
</script>
<style scoped>
h3 {
font-weight: normal;
padding-top: 20px;
padding-bottom: 30px;
}
</style>
As you noticed - within our script
part we export our component:
<script>
export default {
name: "HelloWorld"
};
</script>
This is the place where we can define the name of our component. Now when our component is ready can use it within our App component.
2. Import component
- Open and replace the content of the
App.vue
file with the following: - Add an import statement:
- Within the export default{...} declaration add HelloWorld to components list:
- Now we can use our new component using the <HelloWorld/> tag:
<template>
<div class="app">
<h2>I am App (main component)</h2>
</div>
</template>
<script>
export default {
name: "App"
};
</script>
<style>
.app {
margin: 0 auto;
font-family: sans-serif;
background-color: #ccf7e2;
padding: 10px;
border-radius: 5px;
max-width: 500px;
}
</style>
In order to use the HelloWorld component we have to first import and define it within thescript
part:
<script>
import HelloWorld from "@/components/HelloWorld";
[...]
</script>
export default {
name: "App",
components: {
HelloWorld
}
};
<template>
<div class="app">
<h2>I am App (main component)</h2>
<HelloWorld/>
</div>
</template>

Previous lesson Download Next lesson
Spread the word:
