Sometimes, we may want to add components to our Vue 3 app that’s available throughout the app.
In this case, global components are suitable for this purpose.
In this article, we’ll look at how to register a global component with Vue 3.
Register a Global Component in Vue 3
To register global components with Vue 3, we can use the app.comnponent
method.
For instance, we can write:
main.js
import { createApp } from "vue";
import App from "./App.vue";
import HelloWorld from "./components/HelloWorld.vue";
const app = createApp(App);
app.component("hello-world", HelloWorld);
app.mount("#app");
App.vue
<template>
<div>
<hello-world />
</div>
</template>
<script>
export default {
name: "App",
};
</script>
components/HelloWorld.vue
<template>
<div class="hello">hello world</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: String,
},
};
</script>
In main.js
, we import the HelloWorld
component and pass that into the app.component
method.
The first argument is the component name.
The 2nd argument is the component itself.
Then in App.vue
, we use the component by adding the tag with the given component name.
Then in HelloWorld.vue
, we add some content to the template.
The component name only works when we use the kebab-case for the tag name since we defined it with a kebab-case tag name.
We can use the hello-world
component in any other component since we registered it globally.
Conclusion
We can register a global component easily with Vue 3’s app.component
method.