Components in Vuejs

Vue components are one of the important concept in Vue coding life.This Vue components can be reused in HTML.We can register a component locally and also globally.We can also create dynamic component that we see later. Let us understand how to create a simple component in vuejs.

<html>
<head>
<title>
<script type=text/javascript src=js/vue.js><script>
<head>
<body>
<div id=dvcomponent_1>
      <examplecomponent><examplecomponent>
<div>
<div id=dvcomponent_2>
      <examplecomponent><examplecomponent>                    
<div>
<script type=text/javascript>
vue.component('examplecomponent',{
template:'<div><h1>I am examplecomponent'<h1><div>
});
var vm = new Vue({
        el:"#dvcomponent_1"       
});

var vm1 = new Vue({
        el:"#dvcomponent_2"       
});
<script>
<body>
<html>

in the above .html, we have created 2 div with id dvcomponent_1 and dvcomponent_2 and in javascript two vue instances are created with two divs.We have also created common component from the below syntax.

vue.component('examplecomponent')

Once the component is created the same can be used in any number of vue instances. i.e inside the div with ids dvcomponent_1 and dvcomponent_2

How to register a component globally?

This is the code to register a component globally.

vue.component('examplecomponent',{
template:'<div><h2>i am an examplecomponent<h2><div>'
});

The components can be created using custom element tag i.e <examplecomponent><examplecomponent> This can be viewed by the following screenshot

How to register a component locally?

We can create a same component locally inside the vue instances.Let us see the example and understand the way to create component locally.

                var vm=new vue(
{
                el:'#dvcomponent_1',
                components:{
                    'examplecomponent':{
                                template:'<div><h2>This is local registration of component<h2><div>'
                        }
                    }

});

The above example is the way to register the component locally and which is part of the vue instance.

Dynamic Components

Next we will see, how to create dynamic components in vue.Normally dynamic components are created using <component> <component> and is bounded with a property.

<html>
<head>
<title>
<script type=text/javascript src=js/vue.js><script>
<head>
<body>
<div id=dvdatabinding>
      <component v-bind:is="view"><component>
<div>

<script type=text/javascript>
vue.component('examplecomponent',{
template:'<div><h1>I am examplecomponent'<h1><div>
});
var vm = new Vue({
        el:"#dvdatabinding",
        data:{
                view:'examplecomponent1'
            },
        components:{
                'examplecomponent1':{
                    template:'<div><h1>Dynamic components<h1><div>'
                    }
}
});

<script>
<body>
<html>

See the output in the below screenshot.

Happy Vue Coding !!!