Earlier we’ve seen how we can register a component globally so that we don’t have to import it everywhere. However, with that approach, we include the component code everywhere even if we don’t use them. To avoid this, we can register components locally. Components which we register locally will only be available in the component they’re registered in. To use them in other components, we have to register them again.
Here’s my main.js file where I’ve mapped the components without registering them:
import Vue from "vue";
import App from "./App.vue";
Vue.config.productionTip = false;
const ComponentFoo = { name: "Foo", template: `<div>Foo component</div>` };
const ComponentBar = { name: "Bar", template: `<div>Bar component</div>` };
const ComponentBaz = { name: "Baz", template: `<div>Baz component</div>` };
new Vue({
render: (h) => h(App),
components: {
"component-foo": ComponentFoo,
"component-bar": ComponentBar,
"component-baz": ComponentBaz
}
}).$mount("#app");
Code language: JavaScript (javascript)
And here’s the App.vue component using the above components on demand:
<template>
<div id="app">
<div>Hello</div>
<component-foo></component-foo>
<component-bar></component-bar>
<component-baz></component-baz>
<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)
You can find a working copy of the above code from my repos below: