Getting started with Vue.js - part six

In the sixth part of the course, we will learn how to create components and how they can be reused.


Components

A very cool feature from Vue is that you can split your code into components. In this part of the tutorial, we will turn the .card-image and .media elements into two separate components. We can start with the .card-image by added this code to the top of our <script> tag.

Vue Hero - Introduction - Components

As you can see this makes the code for the card more readable. The new card-image component is also reusable, so you can include it where ever you want. Next, we'll add the necessary JS code to our script tag.

Vue Hero - Introduction - Components two

If you open index.html in your browser now everything should look just the same as it did before :-)
We'll go right over to the component for the .media element. Replace the <div class="media"> with this code:

Vue Hero - Introduction - Components three

What we did now was the we replace the whole <div class="media"> block with just a simple one-liner. We also bind the variable name to a attribute (props) so that we can display this inside the component.
Again we need to add the JS code where we create the actual component:

Vue Hero - Introduction - JS

It's not much new here from the other component. We created a component named "media" and allows the parent to send a property to it called "name".

Tip!

When you're building components it's important to know that inside the back ticks that holds the components HTML that you can only have one root element. So wrap everything inside the components inside a div or similar.

Mini challenge

A component does not have to be very advanced. So in this challenge I want you to turn the number_of_interests with it's surrounding <b></b> tag into a component and show it in the same place where it belongs. This will not be a part of the course so when you're finished you can just remove it.


PreviousNext

Buy me a coffee

I'm working hard to create quality courses and lessons. Please consider buying me a coffee or three to support my work.