The key features of Vue include:
- Declarative Rendering: Vue extends standardHTML with a template syntax that allows you to describe HTML output based on JavaScript state
- Reactivity: Vue automatically tracksJavaScript state changes and efficiently updates the DOM when changes happen.
- Component-Based Architecture: Applications are built using small, self-contained, and reusable components
-
Directives: Special attributes starting with
v-if,v-for, andv-bindthat apply reactive behavior to the DOM. - Virtual DOM: Vue uses a Virtual DOM to minimize actual DOM manipulations, improving performance.
- Gentle Learning Curve: If you know HTML, CSS,and JavaScript, you can start building with Vue quickly.
- Versatility: It can be used as a simple library to enhance static HTML or as a full-featured framework for complex SPAs.
- High Performance: Its lightweight nature and optimized re-rendering make it very fast.
- Great Documentation: Vue is famous in the dev community for having exceptionally clear and thorough official documentation.
As of January 2026, the latest stable version of Vue is 3.5.x. Vue 3 is the current industry standard, having replaced Vue 2 (which reached end-of-life in late 2023).
For modern development, the recommended way to start a Vue project is usingVite.
-
Run the creator tool: Open your terminal and run:
npm create vue@latest - Follow the prompts: Enter your project name and select features (like TypeScript or Vue Router).
- Install & Run:
- Options API: The traditional way where you define logic using an object of options like data, methods,and mounted. Best for smaller components.
- Composition API: Introduced in Vue 3, it uses the setup attribute or function to group logic by logical concern rather than option type. It is better for large-scale applications and reusability.
Directives are special tokens in the markup that tell the library to do something to a DOM element.
- v-bind: Dynamically binds an attribute (e.g.,:src="imagePath")
- v-model: Creates two-way data binding on form inputs
- v-if / v-else: Conditionally renders an element
- v-for: Renders a list of items by looping through an array
A Single-File Component is a file with a .vue extension that encapsulates the structure (HTML), logic (JavaScript), and styling (CSS) of a component in one place. Example (MyComponent.vue):
In large applications, passing data between many nested components becomes difficult. State management libraries provide a "central store" for all components.
- Pinia: The current officially recommended state management library for Vue 3. It is lightweight and has excellent TypeScript support.
- Vuex: The older state management library used primarily in Vue 2 projects.
Lifecycle hooks are built-in functions that allow you to execute code at specific stages of a component's existence, such as when it is created, added to the DOM, or destroyed.
- onMounted(): Called after the component has been mounted.
- onUpdated(): Called after the component has updated its DOM tree due to a state change.
- onUnmounted(): Called after the component has been removed.
Vue Router is the official router for Vue.js. It syncs the browser's URL with Vue's components, allowing you to build Single-Page Applications where the page doesn't refresh when the user navigates to different sections (like /about or /profile).
Vue Router is the official routing library for Vue.js. It integrates deeply with the Vue core to turn a collection of components into a Single-Page Application (SPA). It manages the relationship between the URL in the browser and the components displayed on the screen without requiring a full page reload.
Core Functionalities- Nested Mapping: Allows you to map nested URL paths to nested components.
- Dynamic Routing: Enables paths with parameters (e.g., /user/:id) to render the same component with different data.
- Navigation Guards: Provides hooks (beforeEach, beforeRouteEnter) to run logic, such as authentication checks, before a user enters a route.
- Transition Effects: Built-in support for CSS transitions when switching between routes.
- History Modes: Offers different ways to handle URLs (HTML5 History mode vs. Hash mode).
Key Components & Concepts
| Feature | Description |
|---|---|
<router-link> |
A component used to create navigation links. It renders
as an <a> tag but prevents page
refreshes.
|
<router-view> |
A functional component that acts as a placeholder where the matched component for the current route will be rendered. |
createRouter |
The function used to initialize the router instance with a list of routes and a history mode. |
| Programmatic Navigation |
Using router.push() or
router.replace() to navigate via JavaScript
instead of a link.
|
Comparison: Web Navigation Approaches
| Feature | Standard Multi-Page App (MPA) | Vue Router (SPA) |
|---|---|---|
| Page Load | Full refresh for every new URL. | Only components swap; no refresh. |
| State | State is lost unless saved in cookies/storage. | State is preserved in memory between views. |
| User Experience | Slower transitions due to server requests. | Instant transitions; feels like a desktop app. |
| SEO | Naturally SEO-friendly. | Requires SSR or pre-rendering for optimal SEO. |
Basic Implementation Example
- Define Routes:
- Display in Template:
Both v-if and v-show are used to
conditionally display elements in Vue.js. However, they differ
significantly in how they handle the DOM and when they should be
used for performance optimization.
Comparison Table
| Feature | v-if |
v-show |
|---|---|---|
| Mechanism | Real rendering: Elements are physically added or removed from the DOM. |
CSS-based:
Elements remain in the DOM; only the
display property is toggled.
|
| Initial Render | Lazy: If the condition is false initially, it does nothing until it becomes true. | Eager: The element is always rendered and held in the DOM regardless of the initial state. |
| Lifecycle Hooks |
Triggers mounted, unmounted,
and other lifecycle hooks of child components.
|
Does not trigger lifecycle hooks when toggling. |
| Performance (Toggle) | Higher cost: Expensive to toggle because it constantly destroys and re-creates elements. | Lower cost: Very cheap to toggle as it only switches CSS. |
| Performance (Initial) | Lower cost: Faster if the element is never shown. | Higher cost: Slower if you have many hidden elements on load. |
v-if(Conditional Rendering):- It is "real" conditional rendering because it ensures that event listeners and child components inside the conditional block are properly destroyed and re-created during toggles.
- It supports the
<template>element, allowing you to group multiple elements without adding an extra node to the DOM. - Works with
v-elseandv-else-if.
v-show(Conditional Visibility):- The element is always present in the DOM. Vue simply applies
display: none;to the inline styles when the expression evaluates to false. - It cannot be used on the
templateelement and does not work withv-else.
- The element is always present in the DOM. Vue simply applies
- Use
v-ifwhen:- The condition is unlikely to change frequently during the runtime.
- You want to reduce the initial load time by not rendering components that might never be seen.
- You need to use
v-elseorv-else-iflogic.
- Use
v-showwhen:- You need to toggle something very frequently (e.g., a tab, a tooltip, or a dropdown).
- The element is critical to the layout and should be "ready" in the DOM immediately.
The v-for directive is used to render a list of items based
on an array or an object. It uses a specific syntax:
item in items, where items is the source data
and item is an alias for the element being iterated.
-
Iterating Arrays:
You can access the element and its index:
v-for="(item, index) in items". -
Iterating Objects:
You can iterate through properties:
v-for="(value, key, index) in myObject". -
Range Support:
It can also take an integer to repeat a template a fixed number of
times:
v-for="n in 10".
The Role of the :key Attribute
The :key attribute is a unique identifier used by Vue’s
Virtual DOM algorithm to identify nodes when updating the list. Without
keys, Vue uses an "in-place patch" strategy, which can lead to UI bugs.
| Reason | Detail |
|---|---|
| Efficient Updates | It helps Vue identify exactly which items have changed, been added, or been removed, minimizing DOM manipulations. |
| State Preservation |
Ensures that temporary state (like text in an
<input> or focus) stays with the correct item
when the list is reordered.
|
| Identity | Provides a unique "signature" for each element so Vue doesn't accidentally reuse a component for a different piece of data. |
| Transitions |
Essential for Vue's
<transition-group> to correctly animate items
moving to new positions.
|
Best Practices vs. Anti-patterns
-
Do:
Use unique IDs from your database
(e.g.,
:key="user.id"). -
Don't:
Use
indexas a key if the list can be reordered, filtered, or deleted. Using the index can cause the wrong components to be updated or destroyed. -
Don't:
Use
v-foron the same element asv-if. Vue 3 givesv-ifhigher priority, meaning thev-ifcondition won't have access to variables defined in thev-for.
Implementation Example
In the Composition API, both ref and reactive are used to create reactive state. While they achieve similar goals, they handle data types and access patterns differently.
| Feature | ref |
reactive |
|---|---|---|
| Data Types | Handles any type (Primitives: String, Number, Boolean, or Objects). | Handles Objects and Arrays only (Complex types). |
| Access in Script | Must use .value property (e.g., count.value). |
Accessed directly (e.g., state.count). |
| Access in Template | Automatically unwrapped (no .value needed). |
Accessed directly. |
| Reassignment | Can replace the entire value (even objects). | Cannot replace the whole object; it loses reactivity if overwritten. |
| Destructuring | Maintains reactivity. | Loses reactivity unless used with toRefs. |
Detailed Breakdown
-
1. Handling Primitives
-
ref: Designed to wrap primitive values in an object to make them reactive.
- Example:
const count = ref(0).
- Example:
-
reactive: Cannot hold primitives. If you pass a string or number to
reactive(), it will trigger a Vue warning and won't be reactive.
-
ref: Designed to wrap primitive values in an object to make them reactive.
-
2. Reassignment Risks
-
ref: You can replace an entire object easily:
-
reactive: Overwriting the variable breaks the link to Vue's reactivity system:
-
ref: You can replace an entire object easily:
-
3. Destructuring Behavior
If you destructure a
reactiveobject, the resulting variables become plain values and stop updating the UI. To fix this, you must wrap the object intoRefs().refvariables do not suffer from this issue when passed around.
When to Use Which?
-
Use
refby default: It is more versatile because it handles primitives and objects. Most Vue developers preferreffor consistency. -
Use
reactivefor grouped state: If you have a large form or a collection of related properties that logically belong together in a single object,reactivecan make the code cleaner by avoiding.valueeverywhere.
Computed Properties Overview
Computed properties are reactive functions that allow you to describe a value that depends on other data properties. They are "derived" state—when the source data changes, the computed property automatically re-evaluates and updates.
Key Differences: Computed vs. Methods
The primary difference is caching. Computed properties cache their results based on their reactive dependencies, whereas methods execute every time they are called.
| Feature | Computed Properties | Methods |
|---|---|---|
| Caching | Cached: Only re-calculates when a dependency changes. | No Caching: Runs every time the component re-renders or it is called. |
| Usage | Used as a property (no parentheses: {{ fullName }}). |
Used as a function (with parentheses: {{ getFullName() }}). |
| Performance | Better for expensive logic or heavy data processing. | Can be less efficient if logic is complex and called frequently. |
| Purpose | Designed for data transformation or derivation. | Designed for event handling or specific actions. |
| Side Effects | Should be "pure" (no API calls or DOM changes). | Can contain side effects (API calls, timers, etc.). |
Technical Breakdown
- 1. The Power of Caching: If you have a computed property that filters a massive list, and that list hasn't changed, Vue will return the previously calculated result instantly. A method would force Vue to re-filter the entire list every time any unrelated part of the page updates.
-
2. Dependency Tracking: Vue's reactivity system tracks which variables are used inside a computed property. If
computedValuedepends onfirstNameandlastName, it will only run again if one of those two variables changes.
Best Practices
- Computed for Templates: Always use computed properties for complex logic inside your HTML to keep templates clean and readable.
- Avoid Side Effects: Never try to change other data properties or make asynchronous calls (like
fetch) inside a computed property; use Watchers for those tasks. - Getters and Setters: By default, computed properties are "getter-only," but you can provide a "setter" if you need to manually update the source data when the computed value is changed.
Implementation Example
Watchers Overview
In Vue.js, Watchers allow you to perform "side effects" in response to state changes. Unlike computed properties, which are used to derive new data, watchers are used for asynchronous operations, DOM manipulation, or changing other pieces of state when a specific dependency changes.
Comparison: watch vs. watchEffect
Vue 3 provides two main ways to watch data. While they share a similar goal, they differ in how they track dependencies and when they run for the first time.
| Feature | watch |
watchEffect |
|---|---|---|
| Tracking | Explicit: You must define exactly what to watch. | Implicit: Automatically tracks every reactive property used inside the function. |
| Initial Run | Lazy: Does not run until the watched source changes (can be overridden). | Eager: Runs immediately once the component is initialized. |
| Access to Old Value | Provides both the new value and the old value. | Only has access to the current state. |
| Use Case | Best for specific state changes or when you need the previous value. | Best for logic that depends on multiple sources or needs to run immediately. |
Key Concepts and Features
-
Deep Watching: By default,
watchis shallow. If you want to watch nested properties inside an object, you must set the{ deep: true }option. -
Immediate Execution: You can make a
watchrun immediately on setup (likewatchEffect) by passing{ immediate: true }. - Cleanup Side Effects: Both functions allow you to define a cleanup callback (e.g., to cancel an API request or clear a timer) that runs right before the effect re-runs or when the component is unmounted.
-
Flush Timing: You can control whether the watcher runs before or after Vue updates the DOM using the
flushoption ('pre','post', or'sync').
Practical Examples
Using watch (Specific and Detailed)
Using watchEffect (Automatic and Immediate)
When to use Watchers vs. Computed
- Computed: Use for transforming data to be displayed in the template (Pure functions).
- Watchers: Use for Side Effects such as API calls, logging, changing the URL, or manual DOM updates.
Two-Way Data Binding Overview
In Vue.js, two-way data binding refers to the synchronization between the user interface (View) and the underlying data (Model). When the data changes, the UI updates; conversely, when the user interacts with the UI (e.g., typing in an input), the data updates automatically.
The v-model directive is the primary tool used to achieve this. It acts as "syntactic sugar," combining property binding and event listening into a single attribute.
How v-model Works Internally
While v-model looks like a single operation, it is actually a shorthand for two separate actions:
- Binding a value: It passes a data property to the element (typically via the
valueattribute). - Listening for changes: It listens for an input event and updates the data property with the new value.
| Element Type | Property Bound | Event Listened To |
|---|---|---|
| Text Inputs/Textareas | value |
input event |
| Checkboxes/Radios | checked |
change event |
| Select Dropdowns | value |
change event |
Key Features and Modifiers
Vue provides built-in modifiers to change how v-model behaves during user interaction:
-
.lazy: Instead of updating the data on every keystroke (inputevent), it only updates when the user leaves the input field (changeevent). -
.number: Automatically casts the user input string into a valid JavaScript number. -
.trim: Automatically strips whitespace from the beginning and end of the user input.
Using v-model with Components
In Vue 3, v-model is highly flexible when used on custom components:
-
Default usage: Uses a prop named
modelValueand emits an event namedupdate:modelValue. -
Multiple v-models: You can bind multiple data points to a single component by specifying an argument (e.g.,
v-model:firstName="name"andv-model:lastName="surname").
Implementation Comparison
| Method | Code Example | Manual vs. Automatic |
|---|---|---|
| Manual Binding | <input :value="text" @input="text = $event.target.value"> |
Manual (verbose) |
| v-model | <input v-model="text"> |
Automatic (shorthand) |
Passing Data with Props
In Vue.js, data flows downward from parent components to child components using Props. Props are custom attributes you register on a component; when a value is passed to a prop attribute, it becomes a property on that component instance.
Key Characteristics of Props
- One-Way Data Flow: Data flows down, but not up. If the parent updates the prop, the child updates automatically. However, the child must not attempt to mutate a prop directly.
- Reactive: Props are reactive; if the parent's data changes, the child will reflect those changes immediately.
- Type Safety: You can define the expected data type (String, Number, Object, etc.) to ensure the component is used correctly.
Implementation Steps
| Step | Action | Description |
|---|---|---|
| 1. Define (Child) | defineProps() |
Use this macro in the child component to declare which props it expects. |
| 2. Pass (Parent) | v-bind or : |
Use the colon shorthand to pass dynamic data from the parent's state. |
| 3. Use (Child) | Template/Script | Access the prop in the child's template or script logic. |
Code Example
Child Component (Child.vue)
The child declares the props it is willing to receive.
Parent Component (Parent.vue)
The parent passes the data using the : shorthand.
Prop Validation Rules
It is a best practice to provide requirements for your props. If the requirements are not met, Vue will warn you in the browser console.
- Type: String, Number, Boolean, Array, Object, Date, Function, Symbol.
- Required:
{ required: true }. - Default:
{ default: 'Hello' }or a factory function for objects/arrays. - Validator: A custom function to validate the value logic.
Emitting Events Overview
In Vue.js, while Props allow a parent to send data down, Emits allow a child to send messages or data back up to the parent. This follows the core design pattern: "Props down, Events up".
When a child component triggers an event using $emit, the parent component can listen for that specific event and execute a method or update its own state in response.
Implementation Steps
| Step | Action | Description |
|---|---|---|
| 1. Declare (Child) | defineEmits() |
Declare the events the child is allowed to fire. |
| 2. Trigger (Child) | emit('name', payload) |
Fire the event, optionally passing data known as the payload. |
| 3. Listen (Parent) | v-on or @ |
Use the @ shorthand on the child component tag to catch the event. |
Detailed Code Example
Child Component (ChildButton.vue)
The child declares the event and triggers it on a button click.
Parent Component (ParentView.vue)
The parent listens for increaseBy and receives the payload automatically.
Key Rules and Best Practices
-
Kebab-case for Listeners: While you can use camelCase in JavaScript, Vue recommends using kebab-case in the HTML template (e.g.,
@update-value). -
Validation: You can validate emits in Vue 3 by passing an object to
defineEmitsthat checks if the payload is valid before sending it. - One-Way Data Flow: Never change a prop inside the child to communicate with the parent; always emit an event so the parent can change its own state.
-
Multiple Arguments: You can pass multiple arguments as a payload:
emit('update', arg1, arg2).
Teleport Overview
Teleport is a built-in component in Vue 3 that allows you to "transport" a piece of a component's template to a different part of the DOM tree, outside of the component's hierarchical structure.
Even though the element is rendered in a different location (like the <body> or a specific #container div), it still behaves like a normal child of the original component—meaning it can access the component's state, props, and scoped styles.
Why is Teleport Necessary?
In standard Vue development, components are rendered within their parents. However, certain UI elements can be broken by CSS properties like z-index, overflow: hidden, or position: relative in the parent container.
| Use Case | Problem Without Teleport | Solution With Teleport |
|---|---|---|
| Modals/Dialogs | May get cut off by overflow: hidden on a parent. |
Render at the top level of the <body> to avoid clipping. |
| Full-screen Overlays | Hard to manage z-index depth. |
Moves the element to a global container for easy layering. |
| Notifications | Needs to appear on top of all UI. | Teleport to a dedicated #toast-container at the root. |
| Tooltips | Positioning can be skewed by parent transform properties. |
Positions relative to the viewport or body. |
How to Use Teleport
The <Teleport> component requires a to target, which can be a CSS selector string (like an ID or class) or an actual DOM element.
Example: Creating a Modal
Key Features and Behaviors
- Logical vs. Physical: It remains a logical child of the component. You can pass props to it and emit events from it as if it hadn't moved.
-
Disabled State: You can toggle the teleportation using the
:disabledprop. When disabled, the content stays inside the original component structure. -
Multiple Teleports: Multiple
<Teleport>components can send content to the same target element. They will simply be appended one after another. -
Scoped CSS: Styles defined in
<style scoped>will still apply to the teleported content because it remains part of the virtual component tree.
Slots are a powerful distribution mechanism in Vue.js that allow a parent component to inject HTML, components, or plain text into a child component’s template. This makes components highly reusable by allowing the parent to define the "content" while the child defines the "layout".
Types of Slots
| Slot Type | Description | Usage Scenario |
|---|---|---|
| Default Slot | The unnamed, catch-all slot. | Simple wrappers like buttons or alerts. |
| Named Slots | Specific slots identified by a name (using v-slot:name or #name). |
Complex layouts with multiple sections (e.g., Header, Main, Footer). |
| Scoped Slots | Slots that pass data from the child back to the parent. | Lists or tables where the child manages data but the parent defines the UI. |
Understanding Scoped Slots
Normally, a parent cannot access data inside a child's scope. Scoped Slots bridge this gap by allowing the child to "provide" data to the slot's content in the parent.
The Workflow:
- Child: Defines a
<slot>and binds data to it using attributes (props). - Parent: Receives that data via the
v-slotdirective value.
Implementation Example
Child Component (UserList.vue):
The child iterates through data but lets the parent decide how to display each item.
Parent Component:
The parent accesses the userData via the #item slot.
Key Benefits of Scoped Slots
- Inversion of Control: The child manages the logic (fetching, filtering, or looping), while the parent manages the visual representation.
- Flexibility: You can use the same component for a "Card View" in one part of your app and a "Table View" in another, just by changing the slot template.
- Encapsulation: Keeps the child component focused on data/state management without hardcoding UI styles.
KeepAlive Overview
<KeepAlive> is a built-in component in Vue that caches component instances when they are dynamically toggled.
Normally, when a component is switched out (e.g., via v-if or <component :is="...">), it is destroyed and its state is lost. Wrapping these components in <KeepAlive> preserves their state and avoids the performance overhead of re-creating the DOM and re-fetching data.
Key Behaviors and Lifecycle
When a component is cached by <KeepAlive>, its standard lifecycle hooks behave differently, and two specialized hooks are introduced:
| Lifecycle Hook | Behavior Inside <KeepAlive> |
|---|---|
onMounted |
Only fires the first time the component is created. |
onUnmounted |
Never fires while the component is being cached. |
onActivated |
Fires every time the component becomes visible (re-enters the DOM). |
onDeactivated |
Fires every time the component is hidden (removed from DOM but kept in memory). |
Core Properties
You can control which components are cached using the following props:
include: Only components with matching names will be cached (String, Regex, or Array).exclude: Any component with a matching name will not be cached.max: Limits the maximum number of component instances to cache. When the limit is reached, the least recently used (LRU) instance is destroyed.
Common Use Cases
| Use Case | Benefit |
|---|---|
| Tabbed Interfaces | Switching between tabs preserves the user's scroll position and form input values. |
| List Views | Navigating back from a "Detail" page to a "List" page doesn't trigger a new API call to reload the list. |
| Multi-step Forms | Prevents data loss when a user navigates back to a previous step to make corrections. |
Implementation Example
Example: Caching Dynamic Components
Asynchronous Components Overview
In large applications, loading every component at once can lead to a massive initial JavaScript bundle, causing slow page loads. Asynchronous Components allow you to split your app into smaller chunks and load components from the server only when they are actually needed.
In Vue 3, this is achieved using the defineAsyncComponent function.
Implementation Approaches
| Method | Description | Use Case |
|---|---|---|
| Basic Usage | A simple function that returns a Promise (usually via a dynamic import()). |
Standard route-level or tab-level components. |
| Advanced Options | An object configuration that handles loading and error states. | Mission-critical components where user feedback during loading is required. |
| With Suspense | Integration with the <Suspense> built-in component. |
Coordinating multiple async dependencies (like data fetching + component loading). |
Basic vs. Advanced Syntax
1. Basic SyntaxThe most common way to lazy-load a component:
For a better user experience, you can manage the "waiting" period:
Key Benefits
- Code Splitting: Build tools like Vite or Webpack automatically recognize dynamic imports and create separate
.jsfiles for them. - Reduced Initial Load: Users only download the code for the page they are currently visiting.
- Improved Performance: Smaller entry bundles lead to faster "Time to Interactive" (TTI).
Using with <Suspense>
Vue 3's <Suspense> component can coordinate the loading state of an entire tree of async components. It provides "slots" for the ready state and the loading (fallback) state.
Provide and Inject Overview
Provide and Inject is a feature in Vue used for dependency injection. It allows a "grandparent" or ancestor component to serve as a dependency provider for all its descendants, regardless of how deep the component hierarchy is.
This solves the problem of "Prop Drilling," where data must be passed through multiple layers of intermediate components that don't actually need the data themselves.
How It Works
| Action | Component | Macro / Function | Description |
|---|---|---|---|
| Provide | Ancestor | provide(key, value) |
Defines the data or methods to be shared with descendants. |
| Inject | Descendant | inject(key, default?) |
Retrieves the data provided by an ancestor using the unique key. |
Provide/Inject vs. Props
| Feature | Props | Provide / Inject |
|---|---|---|
| Data Flow | Direct (Parent to Child). | Long-distance (Ancestor to any Descendant). |
| Coupling | High: Components must be explicitly linked. | Low: Intermediate components are unaware of the data. |
| Scalability | Becomes messy with deep nesting (Prop Drilling). | Clean for global-like state within a specific tree. |
| Visibility | Explicit in the template. | Implicit; can be harder to track where data originates. |
Implementation Example
The Ancestor ComponentBest Practices
- Reactivity: To keep the injected data reactive, ensure you provide a
reforreactiveobject. - Symbol Keys: For large applications, use Symbols as keys instead of strings to avoid naming collisions between different plugins or components.
- Mutations: If a child needs to change the data, it is best practice to provide a function (like
toggleTheme) that performs the mutation in the ancestor, rather than letting the child mutate state directly. - Plugin Usage: This pattern is the primary way Vue plugins (like Vue Router or Pinia) make their instances available to your entire app.
Component Registration Overview
In Vue.js, you must register components so that Vue knows how to locate and render them when they are used in a template. There are two primary ways to do this: Global and Local registration.
Comparison Table
| Feature | Global Registration | Local Registration |
|---|---|---|
| Declaration | Registered on the app instance (app.component). |
Registered within a specific component file. |
| Availability | Available everywhere in the application. | Only available in the component that imports it. |
| Bundle Size | Heavier: Included in the main bundle even if unused. | Lighter: Supports tree-shaking; only loaded if needed. |
| Dependency Tracking | Harder: Difficult to see where a component is used. | Clear: Explicit imports make dependencies easy to trace. |
| Best For | Common UI elements (Buttons, Inputs, Icons). | Feature-specific or complex sub-components. |
Implementation Differences
1. Global RegistrationRegistered in the main entry file (usually main.js). Once registered, you do not need to import them again in any .vue file.
The component is imported and used only where it is needed. This is the recommended approach for most components.
Pros and Cons
- Pros: Extremely convenient for "building blocks" (Base components) used in almost every view.
- Cons: It creates a "Global Namespace" which can lead to name collisions. It also bloats the initial JavaScript file because build tools cannot remove unused global components.
- Pros: Keeps the relationship between components explicit. Improves performance through tree-shaking.
- Cons: Can feel repetitive if you have to import the same 5-10 "Base" components in every single file.