How to create global components in Vue.js

in Code Write a comment

In this tutorial, you’ll learn how to register component globally, so that you can re-use it in within your Vue.js app.

If you want to learn how to import a component inside another component you can read my previous article.

Let’s create our globalComponents.js file, where we’ll declare all the necessary components. You can add this file in the same directory as your main.js file.

import Porfolio from '@/components/Projects/PorfolioProjects'

const GlobalComponents = {
  install (Vue) {
    Vue.component('porfolio-projects', Porfolio)
  }
}

export default GlobalComponents

Hi, I'm Renat 👋

 


We’ve just created our first global component <porfolio-projects</porfolio-projects>. Now we need to import globalComponents.js file inside the main.js.

import GlobalComponents from './globalComponents'

All done. You can now re-use <portfolio-projects></portfolio-projects> component in your app without importing it each time.

I usually declare loader animation and some form fields as global components. It saves a lot of time.

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-global-components

PS: Make sure you check other Vue.js tutorials, e.g. how to call a child function using refs in Vue.js

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment