10). VUE.JS Components basic and depth understanding

Component Basic Information



Components makes your code more reusable and your markup more readable.


When registering a component, it will always be given a name.
The template key is where you write your markup for that component. In the same object you’ll later add more functionalities. 

Vue.component('header-component', {
        template: '<div>A custom header component!</div>'
})

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

You create an instance of your component through adding <header-component></header-component> in the HTML:

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

Props

Props will enable you to pass data into a component instance from the outside of that component. or more correctly, pass the data down from a parent.

//My-component is child component
Vue.component('my-component', {
        props: ['message'],
        template: `<div>{{ message }}</div>`,
})

//Main Component is parent component and we pass message from parent to child like below.

<div id="app">
     <my-component v-bind:message="msg"></my-component>
     <my-component v-bind:message="msg1"></my-component>
</div>

var app = new Vue({
       el: '#app',
       data: {
             msg: 'Hello from the Vue instance first called of my-component ',
             msg1: 'Hello from the Vue instance second called of my-component'
       }
})

Now, it will display like below:

'Hello from the Vue instance first called of my-component '
'Hello from the Vue instance second called of my-component '


Component in-depth understanding

There are two way register component 
  1. Global Registration
  2. Local Registration

Global Registration



When we register components using Vue.component. These components are globally registered. That means they can be used in the template of any root Vue instance (new Vue) created after registration. just like below.

Vue.component('my-component-name', {
// ... options ...
})

Local Registration

f you’re using a build system like Webpack, globally registering all components means that even if you stop using a component, it could still be included in your final build. This unnecessarily increases the amount of JavaScript your users have to download.

For define your local components is same as plain JavaScript objects, just look like below:

var ComponentA = { /* ... */ }

Then define the components you’d like to use in a components option:

new Vue({
       el: '#app'
       components: {
               'component-a': ComponentA,
               'component-b': ComponentB
       }
});

locally registered components are not available in sub components.

Comments

Popular posts from this blog

Angular 4 interview questions and answers for experience

8). Vue.js Methods and Event Handling

12). Vue JS - Slots