← Back to Vue.js Course | Chapter 4: Components | Lesson 7 of 7

Component registration

Components can be registered globally for the whole app or locally inside a single component.

In this page:

  1. Component registration
Syntax
markup
const app = Vue.createApp({});
app.component('component-name', definition);    // global

export default {
  components: { LocalComponent }    // local
}

Component registration

app.component makes a component available everywhere but bundlers cannot tree-shake it. Local registration through the components option makes dependencies explicit and keeps bundles smaller.

In single-file components with script setup, imported components are usable automatically.

Note: Prefer local registration for components used in only a few places.

Example: Component registration

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <global-tag></global-tag>
  <parent-box></parent-box>
</div>
<script>
  const LocalChild = { template: "<i>local child</i>" };
  const app = Vue.createApp({});
  app.component("global-tag", { template: "<p>I am global</p>" });
  app.component("parent-box", {
    components: { "local-child": LocalChild },
    template: "<p>Parent uses: <local-child></local-child></p>",
  });
  app.mount("#app");
</script>
</body>
</html>

<!-- Output:
Rendered: I am globalParent uses: local child
-->
Live Example
Related Topics
Common Mistakes
  1. Registering everything globally
  2. Expecting a locally registered component to work in children
  3. Forgetting the components option
Chapter Summary
  • app.component is global
  • components option is local
  • Local registration aids tree-shaking
  • Children do not inherit local components
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.