Components Intro


What are Vue Components?

Vue Components are a way to extend HTML elements. In other words, Vue components are a way to create your own HTML elements. 

Vue components let you encapsulate reusable code. 

Vue components are the main base of SPAs (Single Page Applications).


Registering Vue Components

Obviously Vue components need to be defined and registered to be recognized in our Vue application. 

Vue components can be registered in one of two ways: 

  • Globally
  • Locally 

No matter which method you choose, make sure the component is registered before you instantiate the root Vue instance. 


Registering global components

Here is how we define and register a Vue component globally:

Vue.component('component-name', {
template: '<div><p>Some custom elements</p></div>'
});

Since we registered our component globally all Vue instances created after it will recognize it:

new Vue({
el: '#app'
});

Now everything is ready and we get to use our component:

<div id="app">
<component-name></component-name>
</div>

Remember when I earlier said "Vue components let you encapsulate reusable code"? Well:

<div id="app">
<component-name></component-name>
<br>
<component-name></component-name>
</div>

I can use it as many times as I want. This keeps your HTML code extremely clean and easier to read. 


Registering local components

By registering your Vue components locally, you make them available only in the scope of a Vue instance.

var myComponent = {
template: '<div><p>Some custom elements</p></div>'
};
new Vue({
el: '#app',
components: {
'component-name': myComponent
}
});

At first glance the global option looks an easier approach and I think it's fine for small projects. But in bigger Vue applications, the local registration makes it easier to keep track of your components.


Comments: