Vue.js Components

Vue.js components let you build encapsulated, reusable, and modular blocks of code. They help you break down large user interfaces into smaller, manageable pieces. Whether you're working on a small web app or a complex single-page application, components improve structure and maintainability.



What Are Vue.js Components?

A Vue component is a self-contained unit of UI that includes its HTML, CSS, and JavaScript logic. You can define components once and reuse them anywhere in your application.

Vue supports two types of components:

  • Global components: Available throughout the app.
  • Local components: Registered only within a specific component.

Each component typically includes:

  • A template (UI structure)
  • A script (logic)
  • Optional styles (CSS)

Benefits of Using Vue Components

Using components helps you:

  • Reuse code efficiently
  • Simplify debugging and testing
  • Separate concerns for better organization
  • Enhance scalability of your application

Creating a Vue Global Component

<!-- Register a global component -->
<script src="https://cdn.jsdelivr.net/npm/vue@3"></script>
<script>
  const { createApp } = Vue;

  const app = createApp({});

  app.component('user-card', {
    props: ['name', 'email'],
    template: `
      <div class="card">
        <h3>{{ name }}</h3>
        <p>{{ email }}</p>
      </div>
    `
  });

  app.mount('#app');
</script>

<!-- Use the component -->
<div id="app">
  <user-card name="Amit Kumar" email="[email protected]"></user-card>
</div>

This example creates a global component user-card, which accepts name and email as props and displays them in a styled layout.

Creating a Vue Local Component

<div id="app">
  <user-list></user-list>
</div>

<script>
  const { createApp } = Vue;

  const UserCard = {
    props: ['name'],
    template: `<div><strong>{{ name }}</strong></div>`
  };

  const UserList = {
    components: {
      'user-card': UserCard
    },
    data() {
      return {
        users: ['Ravi', 'Sarah', 'John']
      };
    },
    template: `
      <div>
        <user-card
          v-for="(user, index) in users"
          :key="index"
          :name="user"
        ></user-card>
      </div>
    `
  };

  createApp({
    components: {
      'user-list': UserList
    }
  }).mount('#app');
</script>

This example defines UserCard and UserList as local components. UserList loops through a list of names and renders a UserCard for each.

Passing Data to Components with props

Props allow parent components to pass data to child components. This keeps components flexible and reusable.

Example:

props: ['title']

You can also define props with validation and default values:

props: {
  title: {
    type: String,       // expects a string
    default: 'Untitled' // used if no value is passed
  }
}

In the template, you bind the prop like this:

<my-component title="Dashboard"></my-component>

Inside the component, you access title just like any other data property. Using props ensures each component receives only the data it needs.

Emitting Events from Child to Parent

Child components can communicate back to parent components using $emit method.

<!-- Child Component -->
<template>
  <button @click="$emit('notify', 'Clicked!')">Notify</button>
</template>

<!-- Parent Component -->
<child-component @notify="handleNotification"></child-component>

In the parent, you define handleNotification to respond to the emitted event.

Single File Components (SFC)

Vue's Single File Components (.vue files) are ideal for real-world projects. They contain <template>, <script>, and <style> sections in one file.

<!-- UserCard.vue -->
<template>
  <div>
    <h4>{{ name }}</h4>
  </div>
</template>

<script>
export default {
  props: ['name']
};
</script>

<style scoped>
h4 {
  color: teal;
}
</style>

You can then import and use this component in another Vue file.

Conclusion

In this tutorial, you learned how Vue.js components help organize and reuse code by breaking interfaces into smaller, manageable parts. You explored creating global and local components, passing data with props, handling events with $emit, and structuring Single File Components. These skills are essential for building clean, scalable, and efficient Vue.js applications.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram