You can use a component anywhere in your application without importing by registering the component globally. You should keep in mind it’s drawback though. When you register a component globally, you’re asking Vue.js to include the component mounting code in the codebase whether you use it or not. So, make sure you only register the components globally you’re completely certain of using them somewhere.
You can register a component globally by using the Vue.component() method. Here’s an example to demonstrate the same. Here’s the main.js where I registered the components globally:
import Vue from "vue";
import App from "./App.vue";
Vue.config.productionTip = false;
Vue.component("component-foo", {
template: `<div>Foo component</div>`
});
Vue.component("component-bar", {
template: `<div>Bar component</div>`
});
new Vue({
render: (h) => h(App)
}).$mount("#app");
Code language: JavaScript (javascript)
You can then use these components wherever you want. Here’s my App.vue file using these components:
<template>
<div id="app">
<component-foo />
<component-bar />
<div class="np-credits">wwww.nightprogrammer.com</div>
</div>
</template>
<script>
export default {
name: "App",
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
padding: 24px;
}
.np-credits {
font-size: 12px;
margin-top: 12px;
color: #4b4b4b;
}
</style>
Code language: HTML, XML (xml)
Links to the working version of the above code is given below: