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
| Type | Global | Local |
|---|---|---|
| Components | Vue.component('name', {}) | components: { Name } |
| Directives | Vue.directive('name', {}) | directives: { name: {} } |
| Filters | Vue.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
| Register | When |
|---|---|
| Globally | Used in many components across the app (e.g., a Button component) |
| Locally | Used 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