How to register a Global component in Vue 3 and Vue 2

featured Image

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

Related Posts

featured Image

How to add common header and footer in vuejs.

Here, in this article, we will learn how to add a common header and footer component in our vuejs application. In general, we always have the same header and footer…

Read more
featured Image

How to call a function in VUE template?

Here, we will learn on how to call a function in vue template. First, we have to define the function in the methods. and then we can use an event…

Read more
featured Image

How to redirect to external url in vue

Here, we will learn how to redirect to an external URL in vuejs application. Page Navigation is one of the basic features of a website. It helps us to navigate…

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *