In this post, we will see how we can register a component globally in Vue 2 and Vue 3.

In Vue, we can register a component in two ways: Locally and Globally

Global components are one that can be used anywhere in the application, whereas a local component cannot be used anywhere, it can only be used in those components where it is registered using components property in Vue

Let's register a Global component in both Vue 2 and Vue 3.

Register a Global component in Vue 3

In Vue 3, to register a component globally we will use the app.component() method.

Let's say we have component <GlobalComponent /> which we need in almost every component in our application.

So to register it globally, we will open main.js file and use the app.component() method.

import { createApp } from 'vue';
import GlobalComponent from './GlobalComponent.vue';

const app = createApp({})

app.component('GlobalComponent', GlobalComponent);

Once the component is globally registered in Vue 3 , we can use the template anywhere without importing it a second time in our components.

Register a Global component in Vue 2

In Vue 2, to register a component globally we will use the Vue.component() method.

We have to open the main.js file and import the component using Vue.component() method.

import Vue from 'vue';
import GlobalComponent from './GlobalComponent.vue';

Vue.component('GlobalComponent', GlobalComponent);

Now in Vue 2 too, you can just use the template in any other component without importing it again.

Note: Register a component globally, only when it is used almost everywhere in your application.


Related Topics:

How to add common header and footer in vuejs.

How to pass multiple props to a component in Vue

How to pass data from parent component to child using props in Vue

How to get data from the child component in Vue

Update Parent data from child component in VueJs


💾 Recommended Articles