How to register a Global component in Vue 3 and Vue 2
Short article on how to register a component globally in Vue 2 and 3 to be used in any component without importing in every component.
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
Related Posts
Easy Way to use localStorage with Vue
Short article on how to use local storage with Vue and learn saving and storing data in local storage with the setItem() and getItem() methods.
Force update Vue to Reload/Rerender component
Short tutorial on how to correctly force update Vue.js component to reload or rerender. The component is reinitialized without having to do a browser refresh.
Set and get cookies in a browser in Vue App
Find out how to set and get cookies in a browser for your webpage in Vue using vue-cookies package.
Save vuex state after page refresh in Vue App
Short tutorial on how to save (or persist) data in a vue application using Vuex and vuex-persist npm package.
