This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Ahmet Meliksah Akdeniz
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 mustt 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 out 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.
This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Ahmet Meliksah Akdeniz
Ahmet Meliksah Akdeniz | Sciencx (2022-09-06T19:21:24+00:00) Vue.js Basics Part 6 | Components. Retrieved from https://www.scien.cx/2022/09/06/vue-js-basics-part-6-components/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.