Components allow you to break down the complexibility of your application by creating small chunks of isolated code. A component has it’s own template. Good examples of components are
They can be inserted anywhere in your application. This makes it really easy to write reusable code. Later in this article you’ll see how to create a dropdown component.
Components can be nested as well which makes it easy to create a ‘home’ component containing child components. This way you can create pages for your application.
As you can see, the markup is really clean which lets you have a clear overview of the app. In the above example a
dropdown component is loaded in the
home component and a
carousel component is loaded in the
about act like pages, they are shown based on the
currentPage state. Check out Vue.js docs - Components for detailed information.
Let’s have a look, actually it’s really easy. First create an
Protip: If you have a Codepen you can also fork this pen.
This is the CSS I used, feel free to add your own styles:
Cool! A lazy setup it is. Now, first we will initialize a new Vue instance. This is the entry point of your application.
That was easy! Vue is all set up and we can start building our app. We will create a new component called
my-dropdown. In the HTML add the markup for the dropdown component.
Existing html tags are reserved so they can’t be used as component names. The safest way to name components is by prefixing them. For example:
Next we register the dropdown component:
If everything went right you should have something like this now:
At this moment the component is not doing much yet. Since I like clicking stuff we will add some functionality to the component. The default behaviour of a dropdown is to toggle the visibility of the options. This can be achieved by adding a methods object. We create a
close function. These methods will update a data property called
Sweet! Now the data and methods are defined we can implement them in our template. When a user clicks the component we want the options to show/hide. Let’s see how this looks:
We are getting there! Clicking the dropdown component now will update the
The content of the dropdown is still static content, we just repeated the option element 3 times. Let’s add some data in our component:
And then we use the data in our template:
@click binding on
div.option. We still need to create this method. It will set the
selected state and
close the dropdown.
High five! You’ve created your very first Vue component! As you can see it is really easy to get started with the basic concepts of Vue.