Components in Vue 3

Components in Vue 3

As programmers, we all know that reusing logic and source code as much as possible is the best practice. Note that, sometimes we have to write complex HTML ( including style, script ) to render UI and we end up using the same logic multiple times which can turn our pages into a mess.

Components in the programming world aim to solve such problems. It aims, Splitting UI into reusable pieces and each piece responsible for a small set of core logic that encapsulates as reusable code.

In Vue.js components are the most important and powerful feature. we can abstract large application interfaces into small reusable components. Let’s take a deep dive!

Reusable Components in Vue 3
Components in Vue 3

Components in Vue 3

Almost any type of application can be abstracted or organized into a group of components. For example in our application design, we are having header, footer, menu, content area etc. Here we can create each piece as a component and organize all into a single core as a page effectively.

In Vue.js, components are reusable instances and that can be created with the below anatomy.

Component Anatomy

import { createApp } from "vue";
import App from "./App.vue";

const customComponent = {
  components: {
    // mention sub components, if we used in the template
  },
  // the parameters which component accepts
  props: {
    color: String,
    label: {
      type: String,
      required: true,
      default: "none",
      validator: function(value) {
        // should return true, if the prop is valid
        return !!value;
      },
    },
  },
  // the reusable html element
  template: `<button :style="{ color: color }">
          {{ label }}
          </button>`,
};
const app = createApp(App);
// register the component globally
app.component("CustomButton", customComponent);
app.mount("#app");

Here, we have created a Vue.js component named CustomButton. The component object has below properties,

  1. components – mention sub components
  2. props – the parameters component accepts
  3. template – html element

In Addition, setup hook plays a major role. You can learn about it from Setup function in Composition API – Vue 3 topic.

Reusable Components in Vue 3

We can reuse CustomButton based on our needs.

<template>
  <div>
    <CustomButton label="Red" color="red" /> // create red button
    <CustomButton label="Green" color="green" /> // create green button
    <CustomButton label="Blue" color="blue" /> // create blue button
  </div>
</template>

In the above example, we are passing prop attributes( label, color ). The prop attributes will become property of the component instance. So the props are accessible inside the template tag.

Note that, each component maintain its own state. it’s because whenever we use the components, a new instance created for the same.

Global Registration

Here the components registered globally for the application which means it can be used in any template of the application.

const app = Vue.createApp({})

app.component('add-button', {
  /* ... */
})
app.component('save-button', {
  /* ... */
})
app.component('delete-button', {
  /* ... */
})

app.mount('#app')

So we can use above component in any template of our application now,

<div id="app">
  <add-button></add-button>
  <save-button></save-button>
  <delete-button></delete-button>
</div>

Local Registration

In the real time project, global registration is not preferred. Because if we are using a build system like Webpack, global registration loads all components in the build irrespective of component usage in our application. This will increase the script file size unnecessarily.

So Vue.js introduced local registration for components. Here we can create plain objects as like below first ,

const ComponentOne = {
  /* ... */
}
const ComponentTwo = {
  /* ... */
}
const ComponentThree = {
  /* ... */
}

Next, we have to map above object to component property in the Vue.js application instance as like below,

const app = Vue.createApp({
  components: {
    'component-one': ComponentOne,
    'component-two': ComponentTwo,
    'component-three': ComponentThree
  }
})

Here another important point is, local registered components not available in our subcomponents. Let me explain with the below example, Here ComponentOne used in ComponentTwo so we have to mention the same in ComponentTwo Object.

const ComponentOne = {
  /* ... */
}

const ComponentTwo = {
  components: {
    'component-one': ComponentOne
  }
  // ...
}

Custom Events in Components Vue 3

Children - Emit the event

Parent - Listen to the event

Custom events are another interesting topic of Vue.js Components. In the component hierarchy some time we came up to communicate back to the parent from child component. In that situation, Parent listen to any events from the child where the child emits the event.

Emit event in the Child.vue

<button @click=”$emit(‘/** custom event name **/’)” />
<button @click=”$emit(‘btn_click’)” />

Listen to the event in Parent.vue

<Child @/** custom event name **/=”/** event callback method **/”
<Child @btn_click=”onBtnClickCallback”

Conclusion

So component helps widely when we build large scale applications. Reusable sources is the main objective of any component rather than Vue.js Components. Note that, the common application can be organized into nested components which means every part of the page is component here. That’s the power of component function!.

Leave a Reply

%d bloggers like this: