Vue.js Basics Part 6 | Components
Ahmet Meliksah Akdeniz
Posted on September 6, 2022
Components
Today, I will be talking about components
in Vue.js.
This is part 6 of my Vue.js Basics series, to read part 5, please click here (spoiler! Part 5 is about watch property)
We will need components when creating web applications most of the time. Why? Because it's easier to produce and maintain this way.
So, we've got parent and child components. I will share an image first, then explain on it, so it'll be easier to understand.
As you can see from the image above, we've got several components. This image is from Medium. Most of the time, main component is App.js
. That's where we bring all our components together. Then, we've got smaller components for topbar, hero, cards, card and so on. Bottom of the image, you can see 'Card component', and 'Cards component'. This means, we can reuse components that we create in Vue. Imagine the information in the cards come from an API, all we need to do is sending props
and looping 'card component' so we can have them dynamically. I will talk about props
in a later post.
Let's see how this works in code. I'm still coding in Vuejs tutorial by the way.
<script>
import ChildComp from './ChildComp.vue'
export default {
components: {
ChildComp
}
}
</script>
<template>
<ChildComp />
</template>
Code above is 'App.vue' file. To use a child component, we need to import it first. Like so; import ChildComp from './ChildComp.vue'
. Syntax is like this import something from path
. So, we can name it however we want to name it, but path must be exact, otherwise it won't work. Naming that makes sense is best practice, so please don't name it whatever you want to name it even though technically you can
After importing our child component, we need to register it in components
object as code above has done. Finally, we can use our child component <ChildComp />
like this, syntax is <ComponentName />
.
Obviously, to import and use something, we need to have that something. So, here's our child component's code
<template>
<h2>A Child Component!</h2>
</template>
That's it for part 6, we talked about components in Vue.js.
Next, I will be going through props in Vue.
Posted on September 6, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.