Introduction

Components in Vue are like widgets. We can write reusable custom elements the way we want. Components are nothing but objects consisting of all the options contained by root or Vue instance.

In general, there are two ways to register a component

(1) Globally
(2) Locally

Global registration isn’t ideal in all cases, but what if you want to share the same child components in many components? Let’s learn how to register common components globally in VueJS!

Prerequisites

Before moving forward we hope you are aware of-

1. Basic knowledge of Vue.js
2. Vue CLI set up

Tutorial Goal

So what will we cover in today’s tutorial on the best way to register common components globally in VueJS?

  • Register components locally
  • Register components globally
  • Best way to register common components

Initial Set Up

Let’s assume that we have created a project using the vue cli.

To understand this, let’s take, for example, the most commonly created components we’ll use throughout the app. We have common base components such as BaseInput, BaseButton, BaseCard, BaseCheckbox, BaseForm, BaseSelect, etc., with basic functionalities.

Local Registration

In order to use these base components, we have to import and register components in the script section of each parent component as shown below:

import and register components in the script section

With this, we have successfully registered each component locally.

We might need to use these components repeatedly. To avoid this repetition, we can register these base/common components globally so that we can use them in several components of our app.

Global Registration

Navigate to the file src/main.js. Import the components and register them as shown below.

Import the components

What's the problem here?

What will happen when our app starts growing and has tons of common components? Do we need to register them one by one and use them? Yes, that can be done, but it’s an inefficient and old-school way of doing it! And whenever we create a new common component, we must go back and forth between the new component and the src/main.js file to register and use them.

What is the better way?

Well, we can register each base component with a few lines of code. For example, BaseButton.vue, BaseInput.vue, BaseCard.vue, and in general, every component that has the pattern Base*.vue (in this case). Let’s see its implementation.

Create Global Component Container
With global registration and using the app.component() method: make components available globally in the current Vue application. Hire Vue developer to get the job done

Best Way to Register Common Components Globally in VueJS

Install the Lodash library using the below command.

Copy Text
npm install lodash --save

Navigate to src/main.js and add the following code to the file.

Import Lodash’s upperFirst and camelCase functions

Copy Text
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

Use require. context to search every component in the src/components/base directory that starts with Base.

Copy Text
const requireComponent = require.context(
  '~/components/base',
    true,
   /Base[A-Z]\w+\.(vue|js)$/
)

Explanation

  • Here, the first argument for require context is the relative path of the components folder, which in our case is ‘~/components/base’.
  • The second argument determines whether to look for subfolders. You can set this parameter to true/false based on the components hierarchy.
  • The third argument we have to pass is the regex to match component filenames, which in our case is Base.

We’re going to convert component names to the pascalCase format.

Copy Text
requireComponent.keys().forEach(fileName => {
  const componentConfig = requireComponent(fileName)

  const componentName = upperFirst(
    camelCase(
      fileName
        .split('/')
        .pop()
        .replace(/\.\w+$/, '')
    )
  )

Now that we have all the components’ names, register them globally.

Copy Text
Vue.component(
 componentName,componentConfig.default || componentConfig
)

Note: For this to work, one must follow the naming conventions while creating components. Without a regular pattern in the names of the components, this trick might not work.

Github Repository

Visit the source code here and feel free to clone the repository. You can try it your way and explore more about it.

Github link: https://github.com/nency-gajjar/best-way-to-register-common-component

Conclusion

And that’s pretty much it! This is how we can register common components globally in VueJS without importing all the components. It can be done within a few lines of code without having to worry about registering the newly created standard components again and again. We hope the step-by-step guideline was useful to you! For more such guidelines on basic and advanced VueJS concepts, visit the VueJs tutorials page. Every blog post has a github source code repository; clone that repo, and start coding.

Why Register Common Components Globally in VueJS?

  • Makes it accessible from any template within your application
  • Optimized solutions for larger application with common functionality
  • Less time complexity

BOOK A 30 MIN EXPERT CALL

Get In Touch

[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.