Vue.js Component

Vue.js Components are fundamental building blocks for developing reusable and modular UI elements in Vue applications. They encapsulate HTML, CSS, and JavaScript logic into reusable components, promoting maintainability, reusability, and separation of concerns. This chapter will provide a comprehensive guide to Vue.js components, covering everything from basic concepts to advanced techniques, with detailed examples and explanations.

What are Vue.js Components?

Vue.js Components are reusable Vue instances with a name that can be registered globally or locally within another Vue instance. They encapsulate HTML, CSS, and JavaScript logic to create custom, reusable elements.

Creating a Vue Component

Global vs. Local Registration

Components can be registered globally using Vue.component or locally within another Vue instance.

Global Registration

				
					<div id="app">
  <my-component></my-component>
</div> <script type="litespeed/javascript">Vue.component('my-component',{template:'<div>A global Vue component!</div>'});new Vue({el:'#app'})</script> 
				
			

Explanation:

  • Vue.component('my-component', { ... }) globally registers a component named my-component.
  • <my-component></my-component> is used in the template of the root Vue instance (#app).
  • The output will render <div>A global Vue component!</div>.

Local Registration

				
					<div id="app">
  <my-local-component></my-local-component>
</div> <script type="litespeed/javascript">const MyLocalComponent={template:'<div>A local Vue component!</div>'};new Vue({el:'#app',components:{'my-local-component':MyLocalComponent}})</script> 
				
			

Explanation:

  • const MyLocalComponent = { ... } defines a local component.
  • components: { 'my-local-component': MyLocalComponent } registers MyLocalComponent locally within the root Vue instance (#app).
  • The output will render <div>A local Vue component!</div>.

Template, Script, and Style Sections

Components can include separate sections for template, script (JavaScript), and style (CSS).

				
					<template>
  <div>
    <h1>{{ title }}</h1>
    <button @click="increment">Increment Counter</button>
    <p>Counter: {{ counter }}</p>
  </div>
</template> <script type="litespeed/javascript">export default{data(){return{title:'Counter Component',counter:0}},methods:{increment(){this.counter++}}}</script> <style scoped>h1 {
  color: blue;
}</style>
				
			

Explanation:

  • <template> contains the HTML structure of the component.
  • <script> defines the component’s logic, including data, methods, and other options.
  • <style scoped> encapsulates component-specific styles.

Passing Data with Props

Prop Declaration

Props allow passing data from parent components to child components.

				
					<div id="app">
  <child-component message="Hello from parent"></child-component>
</div> <script type="litespeed/javascript">Vue.component('child-component',{props:['message'],template:'<div>{{ message }}</div>'});new Vue({el:'#app'})</script> 
				
			

Explanation:

  • props: ['message'] declares a prop named message.
  • message="Hello from parent" passes data from the parent (#app) to the child component.
  • The output will render <div>Hello from parent</div>.

Prop Validation

Props can be validated to ensure expected types and values.

				
					<div id="app">
  <child-component :age="25"></child-component>
</div> <script type="litespeed/javascript">Vue.component('child-component',{props:{age:{type:Number,required:!0,validator:function(value){return value>=18}}},template:'<div>{{ age }}</div>'});new Vue({el:'#app'})</script> 
				
			

Explanation:

  • props: { age: { type: Number, required: true, ... } } validates the age prop as a Number and requires its presence.
  • The validator function ensures the age is 18 or older.
  • <child-component :age="25"></child-component> passes the age 25 to the child component.
  • The output will render <div>25</div>.

Emitting Custom Events

Event Declaration

Child components can emit custom events to communicate with parent components.

				
					<div id="app">
  <child-component @custom-event="handleCustomEvent"></child-component>
  <p>Parent received: {{ eventData }}</p>
</div> <script type="litespeed/javascript">Vue.component('child-component',{template:'<button @click="emitEvent">Click me</button>',methods:{emitEvent:function(){this.$emit('custom-event','Data from child')}}});new Vue({el:'#app',data:{eventData:''},methods:{handleCustomEvent:function(data){this.eventData=data}}})</script> 
				
			

Explanation:

  • this.$emit('custom-event', 'Data from child') emits a custom-event with data from the child component.
  • @custom-event="handleCustomEvent" listens to the custom-event in the parent (#app).
  • The output will display “Parent received: Data from child” after clicking the button in the child component.

Event Handling in Parent Components

Parent components can handle custom events emitted by child components using event listeners.

				
					<div id="app">
  <child-component @custom-event="handleCustomEvent"></child-component>
  <p>Parent received: {{ eventData }}</p>
</div> <script type="litespeed/javascript">Vue.component('child-component',{template:'<button @click="emitEvent">Click me</button>',methods:{emitEvent:function(){this.$emit('custom-event','Data from child')}}});new Vue({el:'#app',data:{eventData:''},methods:{handleCustomEvent:function(data){this.eventData=data}}})</script> 
				
			

Explanation:

  • this.$emit('custom-event', 'Data from child') emits a custom-event with data from the child component.
  • @custom-event="handleCustomEvent" listens to the custom-event in the parent (#app).
  • The output will display “Parent received: Data from child” after clicking the button in the child component.

Component Lifecycle Hooks

Understanding Lifecycle Hooks

Vue.js components go through various stages during their lifecycle, each stage represented by a lifecycle hook.

Common Lifecycle Methods

				
					<div id="app">
  <child-component></child-component>
</div> <script type="litespeed/javascript">Vue.component('child-component',{template:'<div>Child Component</div>',data(){return{message:'Hello Vue!'}},beforeCreate(){console.log('beforeCreate hook')},created(){console.log('created hook')},beforeMount(){console.log('beforeMount hook')},mounted(){console.log('mounted hook')},beforeUpdate(){console.log('beforeUpdate hook')},updated(){console.log('updated hook')},beforeDestroy(){console.log('beforeDestroy hook')},destroyed(){console.log('destroyed hook')}});new Vue({el:'#app'})</script> 
				
			

Explanation:

  • Each lifecycle hook (beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeDestroy, destroyed) corresponds to a different stage in the component’s lifecycle.
  • The console logs show the order in which lifecycle hooks are called during the component lifecycle.

Component Communication

Parent to Child Communication

Parent components pass data to child components using props.

				
					<div id="app">
  <child-component :message="parentMessage"></child-component>
</div> <script type="litespeed/javascript">Vue.component('child-component',{props:['message'],template:'<div>{{ message }}</div>'});new Vue({el:'#app',data:{parentMessage:'Message from parent'}})</script> 
				
			

Explanation:

  • :message="parentMessage" passes the parentMessage data from the parent to the child component.
  • <div>{{ message }}</div> displays the message prop in the child
  • The output will render <div>Message from parent</div>.

Child to Parent Communication

Child components emit events to communicate with parent components.

				
					<div id="app">
  <child-component @child-event="handleChildEvent"></child-component>
  <p>Parent received: {{ eventData }}</p>
</div> <script type="litespeed/javascript">Vue.component('child-component',{template:'<button @click="emitEvent">Click me</button>',methods:{emitEvent:function(){this.$emit('child-event','Data from child')}}});new Vue({el:'#app',data:{eventData:''},methods:{handleChildEvent:function(data){this.eventData=data}}})</script> 
				
			

Explanation:

  • this.$emit('child-event', 'Data from child') emits a child-event with data from the child component.
  • @child-event="handleChildEvent" listens to the child-event in the parent (#app).
  • The output will display “Parent received: Data from child” after clicking the button in the child component.

Communication between Sibling Components

Communication between sibling components often requires using a common parent as a mediator or using a state management pattern like Vuex.

				
					<div id="app">
  <parent-component></parent-component>
</div> <script type="litespeed/javascript">Vue.component('parent-component',{template:`
    <div>
      <child-a @notify="updateFromChildA"></child-a>
      <child-b :message="messageFromChildA"></child-b>
    </div>
  `,data(){return{messageFromChildA:''}},methods:{updateFromChildA(data){this.messageFromChildA=data}}});Vue.component('child-a',{template:'<button @click="notifyParent">Send Data to Parent</button>',methods:{notifyParent(){this.$emit('notify','Data from Child A')}}});Vue.component('child-b',{props:['message'],template:'<div>{{ message }}</div>'});new Vue({el:'#app'})</script> 
				
			

Explanation:

  • child-a emits a notify event with data to its parent (parent-component).
  • parent-component receives the event and updates its data (messageFromChildA).
  • child-b receives messageFromChildA as a prop and displays it.
  • The output will show “Data from Child A” in child-b when the button in child-a is clicked.

Slots

Named Slots

Named slots allow components to accept additional content from parent components.

				
					<div id="app">
  <card>
    <template v-slot:title>
      <h2>Title</h2>
    </template>
    <p>Content goes here</p>
  </card>
</div> <script type="litespeed/javascript">Vue.component('card',{template:`
    <div class="card">
      <header>
        <slot name="title"></slot>
      </header>
      <main>
        <slot></slot>
      </main>
    </div>
  `})</script> 
				
			

Explanation:

  • <template v-slot:title> defines a named slot named title.
  • <slot name="title"></slot> in the card component renders the content passed to the title slot.
  • <slot></slot> renders the default slot content.
  • The output will render a card component with a titled header and content.

Scoped Slots

Scoped slots allow child components to access data from parent components.

				
					<div id="app">
  <parent-component>
    <template v-slot:default="slotProps">
      <child-component :message="slotProps.message"></child-component>
    </template>
  </parent-component>
</div> <script type="litespeed/javascript">Vue.component('parent-component',{data(){return{message:'Hello from parent'}},template:`
    <div>
      <slot :message="message"></slot>
    </div>
  `});Vue.component('child-component',{props:['message'],template:'<div>{{ message }}</div>'});new Vue({el:'#app'})</script> 
				
			

Explanation:

  • <template v-slot:default="slotProps"> defines a scoped slot with slotProps.
  • :message="slotProps.message" passes slotProps.message to child-component.
  • The output will render “Hello from parent” in child-component.

Dynamic Components

Conditional Rendering of Components

Dynamic components allow rendering different components based on conditions.

				
					<div id="app">
  <component :is="currentComponent"></component>
  <button @click="toggleComponent">Toggle Component</button>
</div> <script type="litespeed/javascript">Vue.component('component-a',{template:'<div>Component A</div>'});Vue.component('component-b',{template:'<div>Component B</div>'});new Vue({el:'#app',data:{currentComponent:'component-a'},methods:{toggleComponent(){this.currentComponent=this.currentComponent==='component-a'?'component-b':'component-a'}}})</script> 
				
			

Explanation:

  • :is="currentComponent" dynamically renders component-a or component-b based on currentComponent.
  • toggleComponent switches between component-a and component-b on button click.
  • The output will initially render Component A and switch to Component B after clicking the button.

Components are a core concept in Vue.js, enabling developers to build modular, reusable UI elements. By encapsulating HTML, CSS, and JavaScript logic into components, Vue.js promotes a clean, maintainable architecture and enhances code reusability. Understanding how to create, communicate between, and optimize components is essential for building scalable Vue.js applications. By mastering Vue.js components, developers can efficiently manage complexity, improve code organization, and deliver robust user interfaces.Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India