Vue js Components


Concept Insight

In Vue.js, components are self-contained units that package markup, styling, and behavior together, enabling the reuse of UI parts across a project. Each block serves as an independent element, allowing developers to construct complex layouts from small, maintainable sections.


Purpose of Components

Rather than repeating structure or logic across pages, Vue components encapsulate reusable sections—like buttons, cards, headers, or forms—into clean, modular segments.


Declaring a Component

Vue allows us to define a custom block by using the component method on the Vue instance. Each one is given a name and includes a template. Here's an example:

Vue.component('greet-box', {   
     template: '<p>Hello from a separate unit!</p>' 
});

Once declared, the component can be used as:

<greet-box></greet-box>

Local vs Global Use

  • Global: Usable everywhere once registered with Vue.component(...).
  • Local: Defined inside components: {} within a specific app or parent unit.
const app = Vue.createApp({   
     components: {     
          'local-block': {       
             template: '<p>Used only here!</p>'     
          }   
      } 
});

Data Handling

Each instance of a component should return a new data object to avoid shared state issues between multiple uses:

data() {   
    return {     
      clicks: 0   
    }; 
}

Passing Inputs (Props)

To provide external values to components, Vue uses props. For example:

props: ['title']

Used in the parent like this:

<info-card title="Custom Text"></info-card>

Event Communication

Child components can emit messages back to their parent using:

this.$emit('notify', data);

The parent listens via:

<child-box @notify="handleNotify"></child-box>

Slots for Flexibility

Vue uses as a placeholder for injecting custom HTML into a component:

<template>   
     <div class="wrapper">     
         <slot></slot>   
     </div> 
</template>

Conclusion

Components in Vue provide a smart, clean way to manage UI complexity. They enable scalable architecture through abstraction and code separation.


Prefer Learning by Watching?

Watch these YouTube tutorials to understand VUE JS Tutorial visually:

What You'll Learn:
  • 📌 Vue JS 3 Tutorial - 29 - Components
  • 📌 The Secret to Reusable Components in Vue
Previous Next