What Are Components?
A little HTML, CSS, & JavaScript knowledge if recommended for this course.
Introduction to components
Vue.js, along with other front-end frameworks or libraries have a concept of building applications using components. The reason behind this is to break up our app into smaller pieces, making our project easier to maintain, organise, and debug.
But what is a component? Consider this design from an upcoming project:
This is a countdown app where we add events and they will displayed in date order, we can also see the number of days to the event. We could build this app completely in the App.vue
file, which is considered the root of our project.
Splitting our app into sections
Even though this is not a huge app, it may quickly become crowded and unorganised in one single file. To help with this, we can split our our app into parts or sections:
Like our buttons at the top, these can either be part of the App.vue
, or we could move them into a component.
The events could also be taken out of the App.vue
and placed into a separate component. Isolating the code into a component like this means we now know where to look to edit this code. Rather than scrolling through large files. Also, if there is a problem with this event section, our code is isolated too.
Reusable
The event component only needs to be made once, components can be highly re-usable. For this use, we can loop over each event and pass the component the required information. Including the event title, description, and the date.
This project also includes a form to either add a new event, or to edit an existing one. This would also be a good use case for a component:
When to use components
There are no rules to determine which parts we should make into components. It’s something which you have to judge yourself.
When a file becomes large and hard to maintain, this may be a good sign you need to outsource code into a component. Or you can organise by features, just like with this edit form.