This collection covers frequently asked Vue.js interview questions, including fundamental concepts, implementation details, and best practices. The question are categorized by importance (⭐ to ⭐⭐⭐) based on their relevance to Vue development.
1. Vue.js Data Binding Principles ⭐⭐⭐
Vue 2: Implements data binding through a combination of object property interception and the publish-subscribe pattern. Using Object.defineProperty(), Vue adds getters and setters to component properties, triggering view updates when data changes.
Vue 3: Employs Proxy to create reactive proxies of entire objects. The track and trigger mechanisms handle dependency collection and update propagation, addressing Vue 2's limitations while improving performance.
2. Why Vue 3's Reactivity is Faster ⭐
- Dynamic Property Handling: Vue 3's Proxy automatically detects property additions and removals, making them reactive without explicit methods like Vue.set.
- Object-Level Proxy: Unlike Vue 2's property-by-property approach, Proxy intercepts all operations on an object, reducing overhead.
- Simplified Implementation: Proxy reduces boilerplate code, leading to cleaner, more maintainable codebases.
- Optimized Performance: Proxy's underlying implementation provides more efficient dependency tracking and update triggering.
Proxy Implementation:
const target = {};
const handler = {
get(target, property, receiver) {
// Interceptor logic
return Reflect.get(target, property, receiver);
},
set(target, property, value, receiver) {
// Interceptor logic
return Reflect.set(target, property, value, receiver);
}
};
const proxy = new Proxy(target, handler);
3. Vue.js Lifecycle Hooks ⭐⭐⭐
The Vue lifecycle encompasses component creation, initialization, template compilation, DOM mounting, rendering, updating, and destruction.
Vue 2 Lifecycle
- beforeCreate: Component instance created, but data observation and event configuration not yet set up.
- created: Instance completed data observation; props, methods, data, computed, and watch are available. Component not mounted to DOM.
- beforeMount: Called before mounting begins. Render function called for the first time (virtual DOM).
- mounted: Template compiled and mounted to DOM. DOM elements accessible via refs.
- beforeUpdate: Called before data updates trigger re-rendering and patching.
- updated: Called after data changes cause virtual DOM re-rendering and patching.
- beforeDestroy: Called before instance destruction; instance still fully functional.
- destroyed: Called after instance destruction; all bindings and event listeners removed.
Vue 3 Lifecycle (Composition API)
- onBeforeMount
- onMounted
- onBeforeUpdate
- onUpdated
- onBeforeUnmount
- onUnmounted
4. Component Communication Methods ⭐⭐⭐
- Parent-Child Communication: Props (parent to child), events (child to parent)
- Ancestor-Descendant Communication: provide/inject
- Vue 2 Sibling Communication: Event bus pattern
- Global State Management: Vuex (Vue 2), Pinia (Vue 3)
- Attribute Inheritance: $attrs (down), $listeners (up in Vue 2)
- Direct Instance Access: $parent (parent instance), $refs (child instances)
- Routing Parameters: Passing data through route params/query
- Slot Communication: Named and scoped slots
5. v-model Implementation and Usage ⭐⭐
Purpose: v-model provides two-way data binding syntax, essentially a shorthand for a prop and corresponding event.
Vue 2: Uses value prop and input event by default. Limited to single binding per component.
Vue 3: Uses modelValue prop and update:modelValue event. Supports multiple v-model bindings (e.g., v-model:title) and custom modifiers.
6. State Management: Vuex and Pinia ⭐
Vuex (Vue 2): Centralized state management with:
- state: Centralized data store
- mutations: Synchronous state modifications
- actions: Asynchronous operations that commit mutations
- getters: Computed properties for state
- modules: Namespaced state containers
Pinia (Vue 3): Next-generation state management with:
- No mutations - actions directly modify state
- Better TypeScript support
- Simplified API with automatic type inference
- No modules - flat structure
- Composition API integration
7. Preventing Vuex Data Loss on Page Refresh ⭐⭐
Cause: Vuex stores data in memory, which is lost when the page reloads.
Solutions:
- Browser Storage: Manually sync state with localStorage/sessionStorage
- vuex-persistedstate: Plugin that automatically persists state to browser storage
8. Computed Properties vs. Watchers ⭐⭐⭐
Computed Properties:
- Automatically track dependencies and cache results
- Support only synchronous operations
- Re-evaluate when dependencies change
- Use for derived data based on other reactive properties
Watchers:
- Execute custom logic when data changes
- Support asynchronous operations
- No automatic caching
- Use for side effects like API calls or complex logic
9. Axios Implementation Patterns ⭐
Basic Setup:
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
export default apiClient;
Request/Response Interceptors:
// Request interceptor
apiClient.interceptors.request.use(config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// Response interceptor
apiClient.interceptors.response.use(
response => response.data,
error => {
if (error.response && error.response.status === 401) {
// Handle unauthorized access
}
return Promise.reject(error);
}
);
10. Route vs. Router ⭐
Route: Represents the current navigation information (path, params, query, hash, name).
Router: The Vue Router instance providing navigation methods, route matching, and lifecycle hooks.
11. v-show vs. v-if ⭐⭐⭐
v-if: True conditional rendering. Elements are completely added/removed from the DOM. Lazy rendering - only processes when condition is true.
v-show: CSS-based toggling. Elements remain in the DOM but are hidden with display: none. More efficient for frequent toggling.
12. Vue Data Changes Not Reflected in View ⭐
Vue 2 Limitations:
- Array methods that don't mutate the original array (concat, slice, filter, etc.)
- Adding new properties to objects
- Asynchronous update queue timing
Solutions:
- Use array mutation methods (splice, push, etc.)
- Use Vue.set or this.$set for new object properties
- Use this.$nextTick for DOM access after data changes
13. Why Vue Component Data is a Function ⭐⭐
Components in Vue are reusable. When data is a function, each component instance gets its own copy of the data, preventing state sharing between instances. If data were an object, all instances would share the same data object.
14. Parent-Child Asynchronous Data Flow ⭐⭐⭐
Issue: Child component may render before parent receives asynchronous data, causing initial empty values.
Solutions:
- v-if Conditional Rendering: Render child only when parent data is ready
- Watchers: Monitor prop changes in child component
- State Management: Use Vuex/Pinia for shared state
15. Emitting Multiple Parameters ⭐
Child Component:
methods: {
submitData() {
this.$emit('data-submitted', id, name, value, timestamp);
}
}
Parent Component:
<template>
<child-component></child-component>
</template>
methods: {
handleData(id, name, value, timestamp) {
// Process data
}
}
16. Vue Router Navigation Methods ⭐⭐
- router-link: Declarative navigation component
- this.$router.push(): Adds new history entry
- this.$router.replace(): Replaces current history entry
- this.$router.go(n): Navigates relative to current position (n=0: current, n=-1: back, n=1: forward)
- <router-view>: Router outlet component
17. v-if vs. v-for Priority ⭐
Vue 2: v-for has higher priority than v-if. Filtering should be done with computed properties instead.
Vue 3: v-if has higher priority than v-for. Can use v-if on the same node as v-for, though combining them is generally discouraged.
18. $nextTick Purpose and Implementation ⭐⭐⭐
Purpose: Ensures DOM operations are performed after Vue has updated the DOM in the next event cycle.
Implementation: $nextTick is essentially a wrapper around Promise.resolve().then() or MutationObserver in browsers.
Use Cases:
- Accessing DOM after data changes
- Ensuring components are fully rendered before performing operations
- Handling post-update logic
19. Importance of Key in v-for ⭐⭐⭐
Purpose:
- Efficient DOM updates by identifying elements
- Preserving component state during re-rendering
- Enabling optimized diffing algorithms
Implementation: Vue uses keys to track node identity, allowing it to reuse and reorder elements rather than recreating them.
20. Vue 2 vs. Vue 3 Differences ⭐⭐⭐
- Reactivity System:
- Vue 2: Object.defineProperty with limitations on dynamic properties
- Vue 3: Proxy for full reactivity support
- Composition API:
- Vue 2: Options API with data, methods, lifecycle hooks
- Vue 3: Composition API with setup() function
- Performance:
- Vue 3: Improved virtual DOM diffing, smaller bundle size with tree-shaking
- TypeScript Support:
- Vue 3: Better TypeScript integration with improved type inference
- Fragment Support:
- Vue 3: Components can have multiple root nodes
- New Features:
- Vue 3: Teleport, Suspense, multiple v-model support
21. Why Vue 3 Doesn't Need $set ⭐⭐
Vue 2 Limitation: Object.defineProperty couldn't detect property additions, requiring $set for reactive property creation.
Vue 3 Solution: Proxy can intercept all property operations, including additions and deletions, making $set unnecessary.
22. Vue Router History vs. Hash Mode ⭐
Hash Mode:
- URL includes # symbol
- Uses window.onhashchange for navigation
- No server configuration required
- Works in all environments
History Mode:
- Clean URLs without #
- Uses HTML5 History API
- Requires server configuration to handle fallback routes
- Better for SEO and user experience
23. Computed and Watcher Lifecycle Order ⭐
Initialization: beforeCreate → data → computed → watchers → created
Data Update: beforeUpdate → computed → watchers → updated
24. Vue 2 vs. Vue 3 Diff Algorithm ⭐
Vue 2: Uses a two-ended comparison algorithm that matches nodes from both ends of the list, with fallback to key-based matching when needed.
Vue 3: Improves on Vue 2 with:
- Static tree hoisting
- Patch flags to mark dynamic nodes
- Block tree optimization
- Longest increasing subsequence algorithm for minimal DOM moves
25. Dynamic and Async Components ⭐
Dynamic Components: Switch between components based on conditions using the component element and :is binding.
Async Components: Load components on demand using factory functions or dynamic imports to improve initial load performance.
26. Event Modifiers ⭐
Event modifiers simplify event handling:
- .stop: Prevents event propagation
- .prevent: Prevents default behavior
- .capture: Adds event listener in capture mode
- .self: Only triggers for element itself
- .once: Triggers only once
- .passive: Improves scrolling performance
- .native: For listening to native events on component roots
27. Route Parameter Passing ⭐
- Path Parameters: /user/:id
- Query Parameters: /search?query=vue
- Named Routes: Using route names with params
- Route Props: Passing props directly to route components
28. Preventing Template Flash ⭐
Cause: Uncompiled templates briefly visible before Vue renders.
Solution: Use v-cloak directive with CSS to hide elements until compilation completes:
[v-cloak] {
display: none;
}
<div v-cloak>
{{ message }}
</div>
29. Vue 2 vs. Vue 3 Tree Shaking ⭐
Vue 2: Limited tree-shaking due to CommonJS module structure and default imports of entire Vue instance.
Vue 3: Optimized for tree-shaking with ES module exports and granular API imports, reducing bundle sizes significantly.
30. Vue 3 ref and reactive ⭐⭐
ref:
- Wraps any value type including primitives
- Provides .value property for access
- Supports deep reactivity for objects
reactive:
- Only for object types (objects, arrays, Maps, Sets)
- Direct property access without .value
- Limited replacement of entire objects
31. Why ref Can Replace Entire Objects ⭐
ref maintains a .value property that can be reassigned entirely, while reactive creates a Proxy bound to the original object reference. When replacing a reactive object, the new object isn't automatically wrappped.
32. Why ref Requires .value ⭐
The .value property serves multiple purposes:
- Enables reactivity for primitive values
- Distinguishes between property access and value access
- Maintains consistent API between primitive and object references
- Provides clear boundary for reactive tracking
33. watch vs. watchEffect ⭐
watch:
- Explicitly specifies dependencies
- Provides access to old and new values
- Lazily executes by default
- Better for targeted side effects
watchEffect:
- Automatically tracks dependencies
- No need to specify reactive sources
- Executes immediately during setup
- Better for general side effects
34. toRef and toRefs ⭐
toRef: Creates a ref from a reactive object's property, maintaining reactivity when destructuring.
toRefs: Converts all properties of a reactive object to refs, useful for returning reactive state from composition functions.
35. Vue Performance Optimization ⭐
- Code Splitting: Dynamic imports and route-level code splitting
- Lazy Loading: Async components and lazy-loaded routes
- Virtual Scrolling: For large lists
- Optimized Re-rendering: Proper use of keys, v-once, and computed properties
- State Management: Avoid unnecessary reactivity with shallowRef, markRaw
- Component Design: Smaller, focused components with clear responsibilities
- Build Optimization: Tree-shaking, minification, compression
- Image Optimization: Lazy loading, proper sizing, modern formats
- Server-Side Rendering: Nuxt.js for improved initial load and SEO