Episode 37 of 44

Registering Things Locally

Register components, directives, and filters locally instead of globally — better organization and tree-shaking for production builds.

Registering Things Locally

So far you have registered components, directives, and filters globally. For better organization and smaller bundles, you can register them locally — scoping them to specific components.

Global vs Local Registration

TypeGlobalLocal
ComponentsVue.component('name', {})components: { Name }
DirectivesVue.directive('name', {})directives: { name: {} }
FiltersVue.filter('name', fn)filters: { name: fn }

Local Component

import NinjaCard from './NinjaCard.vue';

export default {
    components: {
        NinjaCard     // Available only in this component's template
    }
};

Local Directive

export default {
    directives: {
        rainbow: {
            bind(el) {
                el.style.color = '#' + Math.random().toString(16).slice(2, 8);
            }
        }
    }
};

Local Filter

export default {
    filters: {
        capitalize(value) {
            return value.charAt(0).toUpperCase() + value.slice(1);
        }
    }
};

When to Use Which

RegisterWhen
GloballyUsed in many components across the app (e.g., a Button component)
LocallyUsed in one or a few components (most components, directives, filters)

Key Takeaways

  • Local registration scopes things to the component where they are needed
  • Locally registered items are not available in child components unless also registered there
  • Prefer local registration for better code organization and smaller production bundles