When we use vue, it's common to register a component within another component. In this tutorial, we're going to look at how you can globally register a component in Vue, so you never have to reference is in your component again - instead you can use it straight in your <template>
tag.
If you are new to Vue, check out our guide on creating your first Vue application before starting.
Registering components in Vue
It's normal in Vue to see something like this, where a component is registered within another component, for use inside the tag:
<template>
<MyComponent />
</template>
<script>
import MyComponent from '../components/MyComponent.vue';
export default {
name: "ParentComponent",
components: {
MyComponent
}
}
</script>
This is useful for components that may not be needed everywhere in the app, but it is quite normal to have a component which is used almost everywhere in your app. To save yourself referencing it in every file, you can globally register it instead.
How to Globally Register a Component in Vue
To globally register a component in vue, open your main.js file. You should see something like this:
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
When we want to globally register a component in Vue, we need to do it in this file. All you have to do is import your component, as you usually would, and then register it using app.component.
import { createApp } from 'vue'
import App from './App.vue'
// Import your component
import MyComponent from '../components/MyComponent.vue';
// Your app
const app = createApp(App);
// Globally register your component
app.component('MyComponent', MyComponent);
// Mount your app
app.mount('#app');
Now we can reference our <MyComponent />
component from anywhere within our Vue app. app.component()
has two arguments - the first is the name we are giving to our component, and the second is the imported component.
As such, we can now simplify our original code to just this:
<template>
<MyComponent />
</template>
<script>
export default {
name: "ParentComponent"
}
</script>
Top comments (0)