A new VueJS component should always be “registered” to make the VueJS framework locate its implementation and when it is used in a template. You can create local and global VueJS components. Let us first understand what a VueJS Global component is.
What is a VueJS Global component
Normally, VueJS creates components and registers them locally. However, if you want the component to be available globally in your VueJS application, you must add it in the app.component()
method.
This is useful for components that have to be used many times at different locations in the application. Instead of redefining them every time, you can create a VueJS Global component
Main steps to create a VueJS global component.
Step 1: Create Component File
Firstly, create a component file, you need to use at multiple locations. For example, a DateTimeComponent, to show the current date on each page of the application.
Create the component file and add in the code as listed below.
<template>
<div id="app">
<p>Date : {{currDateTime()}}</p>
</div>
</template>
<script>
export default {
methods: {
currDateTime() {
const current = new Date();
const date = current.getFullYear()+'-'+(current.getMonth()+1)+'-'+current.getDate();
const time = current.getHours() + ":" + current.getMinutes() + ":" + current.getSeconds();
const dateTime = date +' '+ time;
return dateTime;
}
}
};
</script>
The code above uses the Date function to get the current date. Once retrieved, you can manipulate the current date in many ways.
Step 2: Import the Global Component
Secondly, you will have to import this component into your main.js or app.js files as shown below.
import DateTimeComponent from "DateTimeComponent";
Vue.component('DateTimeComponent', DateTimeComponent);
Step 3: Register the component
Now you should register the component in the components list inside the app.component()
method as shown below.
app.component(
// the registered name
'DateTimeComponent',
)
Step 4: Use the component
That’s all! You may now use the globally registered component in any of your Vude.js files without adding separate imports.
You can access this from anywhere else in your applications just by its name as shown below.
<DateTimeComponent />