1. Understanding Vue.js: Core Features and Browser Compatibility
Vue.js is a progressive framework designed for building user interfaces. Its core architecture centers around a reactive data binding system that automatically synchronizes the view with underlying data changes. As an MVVM pattern implementation, Vue handles the synchronization between the Model and View layers through its internal mechanisms.
Key characteristics include minimalism, data-driven updates, component-based architecture, and modular flexibility.
Vue.js relies on ECMAScript 5 features that cannot be polyfilled, which is why IE8 and earlier versions are not supported.
2. Vue's Reactive Data Binding Implementation
Vue implements two-way data binding by leveraging the Object.defineProperty method to intercept data access and modification operations. This technique, known as data劫持 (data hijacking), allows Vue to detect when properties are read or changed.
When a property is accessed or modified, the custom getter and setter functions execute additional logic, enabling automatic view updates whenever the underlying data changes.
3. MVVM Architecture vs MVC Pattern
MVVM stands for Model-View-ViewModel. The Model represents application data, the View handles UI rendering, and the ViewModel serves as an intermediary that connects Model and View through bidirectional data binding.
Unlike MVC where View and Model are directly connected, MVVM uses the ViewModel as a bridge. Changes in Model automatically propagate to View, and user interactions in View can directly affect Model data.
MVC separates Model and View through a Controller, whereas MVVM provides automatic synchronization between View and Model without manual DOM manipulation when data changes.
4. Vue's Core Concepts
The framework is built on two fundamental principles: data-driven reactivity and component-based development.
5. Vue vs Angular: Key Differences
Vue utilizes ES5 getters/setters for its reactivity system, while Angular implements its own template compilation with dirty checking mechanisms. Vue does not require dirty checking since it tracks dependencies automatically.
Vue requires an el option to specify the mounting element, limiting its scope to that element. Angular operates on the entire document.
6. Vue's Internal Working Mechanism
Vue follows an M-V-VM pattern where the ViewModel acts as the binding layer.
The process involves:
- Creating a virtual DOM tree using document.createDocumentFragment()
- Intercepting data changes through Object.defineProperty getters/setters
- Notifying subscribed Watchers via a publish-subscribe pattern when data mutates
- Updating virtual DOM nodes and subsequently rendering the actual DOM
7. Single Page Application Characteristics
SPAs deliver all content within a single HTML page, with dynamic updates occurring without full page reloads.
Advantages include smooth user experience without page refreshes, efficient resource loading through single bundle downloads, organized code structure using components, and simplified maintenance.
Disadvantages encompass poor SEO performance, lack of browser history support requiring custom implementation, longer initial load times, and inability to use standard browser navigation buttons.
8. React vs Vue: Comprehensive Comparison
Similarities:
- Both support server-side rendering
- Both implement data-driven UI updates
- Both provide state management solutions
- Both utilize virtual DOM concepts
- Both embrace component-based architecture
- Both enable parent-to-child data passing through props
Differences:
| Aspect | React | Vue |
|---|---|---|
| Pattern | Primarily Controller in MVC | Full MVVM |
| DOM Updates | Re-renders entire component tree on state change | Tracks dependencies to selectively update |
| Template | JSX syntax | Single-file components with template sections |
| Data Flow | Unidirectional | Bidirectional with v-model |
| State | Immutable, requires setState() | Reactive, directly modifiable |
9. Benefits of Component-Based Architecture
- Accelerated development velocity
- Reusability across different project sections
- Simplified team collaboration
- Improved maintainability and scalability
10. Vue Component Lifecycle Hooks
Creation Phase:
- beforeCreate: Instance initialized, data and DOM unavailable
- created: Data observables active, DOM not yet mounted
Mounting Phase:
- beforeMount: Template compiled, real DOM not yet inserted
- mounted: Component successfully rendered to DOM
Update Phase:
- beforeUpdate: Reactive data changed, re-render triggered
- updated: Component re-rendered with updated data
Destruction Phase:
- beforeDestroy: Cleanup operations before removal
- destroyed: Instance fully removed, DOM elements remain
Keep-alive Enhancement: Components wrapped in keep-alive gain two additional hooks:
- activated: Component re-enters view
- deactivated: Component exits view
11. Angular's Change Detection Mechanism
Angular cannot natively determine whether data has mutated. It periodically triggers a full digest cycle that traverses all data bindings to detect changes. This approach is inefficient as it performs unnecessary comparisons across the entire scope.
12. Scoped Component Styles
Adding the scoped attribute to a style block ensures CSS rules apply exclusively to the current component:
<style scoped>
.card { color: #333; }
</style>
13. v-if vs v-show Directives
Both control element visibility but with different mechanisms:
| Aspect | v-if | v-show |
|---|---|---|
| Implementation | DOM element creation/destruction | CSS display property toggling |
| Initial Render | Only when condition is true | Always rendered |
| Toggle Cost | Higher (DOM manipulation) | Lower (style change) |
| Use Case | Conditions rarely changing | Frequent visibility toggling |
14. Vue Event Modifiers
Event Modifiers: .stop, .prevent, .self, .once
Keyboard Modifiers: .enter, .space, .up, .down
Form Modifiers: .number, .trim, .lazy
15. Common Vue Directives
- v-if, v-show, v-for, v-on, v-bind, v-model, v-once
16. Multiple Event Handlers
Vue allows binding multiple handlers to a single event:
<input @keyup.enter="handleSubmit" @focus="handleFocus">
17. $mount vs el Configuration
Both mount Vue instances to DOM elements with identical functionality. The el option automatically triggers mounting during instance creation, while $mount provides manual control for deferred mounting when el is not specified.
18. Event Modifier Usage
<!-- Prevent event propagation -->
<a @click.stop="handleClick"></a>
<!-- Prevent default form submission -->
<form @submit.prevent="submitForm"></form>
<!-- Chain multiple modifiers -->
<a @click.stop.prevent="handleLink"></a>
<!-- Form with prevent only -->
<form @submit.prevent></form>
<!-- Single-fire event -->
<button @click.once="doOnce"></button>
<!-- Self-targeting only -->
<div @click.self="handleOwnClick">...</div>
19. Key and Is Attributes
The key attribute helps Vue track element identity, enabling efficient reordering and removal of elements during updates.
The is attribute enables dynamic component switching and HTML element extension:
<component :is="currentComponent"></component>
<table><tr is="my-row"></tr></table>
20. Data Must Be a Function in Components
Component data must be a function returning a fresh object because components are designed for reuse. Using a plain object would create shared references across instances, causing data contamination between components.
Vue instances use plain objects since they are not intended for reuse, eliminating this concern.
21. Unidirectional Data Flow
Data flows downward from parent to child components. When a child needs to modify parent data, it emits an event to the parent, which then updates its data and passes the new value back down.
22. Computed Properties
Computed properties automatically track reactive dependencies and recalculate when underlying data changes.
Function Syntax:
computed: {
totalPrice() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
}
Object Syntax with Getter/Setter:
computed: {
fullName: {
get() {
return this.firstName + ' ' + this.lastName;
},
set(newValue) {
const parts = newValue.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
}
}
}
23. Component Communication Patterns
Parent to Child:
Parent passes data via custom attributes bound with v-bind, child receives through props:
<!-- Parent Template -->
<child-component :user-data="userInfo"></child-component>
<!-- Child Component -->
<script>
export default {
props: ['userData']
}
</script>
Child to Parent:
Child emits custom events with payload, parent listens and responds:
<!-- Child -->
<script>
methods: {
sendUpdate() {
this.$emit('data-changed', updatedValue);
}
}
</script>
<!-- Parent Template -->
<child-component @data-changed="handleUpdate"></child-component>
24. Computed vs Watch
Computed Properties:
- Evaluate immediately on component load
- Re-evaluate whenever any dependency changes
- Ideal for deriving values from existing data
- Can use getters and setters
Watch Properties:
- Do not execute on initial load (configurable)
- Trigger only when the watched variable changes
- Support deep watching and immediate execution options
- Suitable for executing side effects based on data changes
25. Vue.nextTick Usage
nextTick ensures access to updated DOM elements after data changes:
created() {
this.fetchData().then(() => {
this.$nextTick(() => {
// Safe to access DOM here
this.initializePlugin();
});
});
}
Essential when performing DOM operations in created() hook since DOM hasn't rendered yet at that stage.
26. Custom Directives
Global Registration:
Vue.directive('focus', {
bind(el, binding) { /* Initial setup */ },
inserted(el, binding) { /* DOM insertion */ },
update(el, binding, oldValue) { /* Component updates */ }
});
Component-local Registration:
directives: {
check: {
bind(el, binding) { /* binding.value */ }
}
}
Hook parameters include el (DOM element) and binding (directive configuration object).
27. Optimizing SPA Initial Load
- Load vendor libraries from CDN for parallel downloading
- Implement lazy loading for routes and components
- Display loading indicators during initial fetch
28. Form Modifier Functions
trim: Strips leading and trailing whitespace from input
number: Casts bound value to numeric type
lazy: Switches synchronization from input events to change events
29. Vue Router Navigation Guards
Global Guards: to, from, next parameters
In-component Guards:
- beforeRouteEnter
- beforeRouteUpdate
- beforeRouteLeave
Per-route Guards: beforeEnter
30. Navigation Methods
Declarative:
<router-link :to="{ name: 'dashboard' }"></router-link>
Programmatic:
this.$router.push({ path: '/dashboard' });
31. Route-based Code Splitting
Webpack's require.ensure enables on-demand loading:
Standard Import:
import UserSettings from './views/Settings.vue';
Lazy Loading:
const Settings = r => require.ensure([], () => r(require('./views/Settings.vue')));
32. $router vs $route
$router: The VueRouter instance, provides navigation methods and instance properties
$route: The current route object containing name, path, params, query, meta, and hash properties
33. vue-loader Functionality
vue-loader transforms .vue single-file components into JavaScript modules. It enables:
- ES6 syntax in script sections
- SCSS/LESS preprocessing in style sections
- Jade/Pug templating in template sections
34. Query Parameters vs Route Params
| Aspect | params | query |
|---|---|---|
| Definition | Path parameters | URL query string |
| Syntax | Named routes only | Path-based |
| Visibility | Hidden in URL | Visible in URL |
| Behavior | Similar to POST | Similar to GET |
35. Dynamic Route Configuration
Define dynamic segments with colon notation:
{ path: '/user/:userId', component: UserProfile }
Access via this.$route.params.userId
36. Nested Route Definitions
The children property enables hierarchical routing:
{
path: '/dashboard',
component: Dashboard,
children: [
{ path: 'statistics', component: Stats },
{ path: 'reports', component: Reports }
]
}
37. active-class Implementation
This router-link property applies CSS classes to active navigation links.
38. Route Object Properties
| Property | Purpose |
|---|---|
| $route.name | Current route identifier |
| $route.path | Current route path |
| $route.meta | Metadata for route authentication |
| $route.query | Query string parameters |
| $route.hash | URL fragment identifier |
| $route.params | Path parameter values |
39. src Directory Structure
- main.js: Application entry point
- App.vue: Root application component
- views/: Page-level components
- components/: Reusable UI components
- router/: Navigation configuration
- assets/: Static resources like images and fonts
40. Component Import Workflow
- Create component file in components directory
- Import into the using component
- Register in the components option
- Use in template markup
41. Component Lifecycle Purpose
Lifecycle hooks provide execution points throughout the component's existence:
- Instantiation
- Data initialization
- Template compilation
- DOM mounting
- Updates and re-renders
- Cleanup and removal
Initial page load triggers: beforeCreate, created, beforeMount, mounted
42. Lifecycle Hook Selection Guide
- beforeCreate: Initialize loading states
- created: Fetch initial data, complete loading indicators
- mounted: DOM manipulation (prefer nextTick for timing)
- updated: Centralized data processing
- beforeDestroy: Clear intervals, remove event listeners
- destroyed: Complete cleanup operations
43. Slot Content Distribution
Slots provide fallback content placement within components:
<!-- Component Template -->
<div class="container">
<slot>Default fallback content</slot>
</div>
<!-- Usage -->
<my-component>Custom content</my-component>
Unnamed slots receive default slot content. Named slots handle specific content regions.
44. Computed, Watch, and Methods Comparison
Computed Options: get, set
Watch Options: handler, deep, immediate
Methods vs Computed:
- Methods accept parameters, computed cannot
- Computed results are cached, methods execute on each call
- Computed can depend on other computed properties and component data
45. Render Functions
When template syntax is insufficient, the render function creates VNodes programmatically:
render(createElement) {
return createElement('div', {
class: 'wrapper'
}, [
createElement('h1', this.title),
createElement('p', this.content)
]);
}
These VNodes form the virtual DOM tree for efficient updates.
46. Vuex State Management
Vuex centralizes application state in a single accessible store:
// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: { user: null },
mutations: { setUser(state, payload) { state.user = payload; } },
actions: { fetchUser({ commit }) { /* API call */ } }
});
Use Cases: User authentication, shopping cart, media playback controls
47. nextTick Requirement in created Hook
The created hook executes before DOM rendering completes, making any DOM manipulation ineffective. Wrap DOM-dependent code in nextTick callbacks to ensure execution after the DOM updates.
48. Vuex Store Properties
The store maintains reactive state. Component computed properties automatically sync with store data. Mutations trigger reactive updates across all dependent components. Helper functions map state and getters to local computed properties.
49. AJAX Request Placement
In Component Methods: When data serves only that component
In Vuex Actions: When data requires sharing across components or needs caching for reuse. Actions return Promises enabling composition.
50. Vuex Data Flow
- User interaction triggers action via dispatch
- Action executes logic and commits mutation
- Mutation synchronously updates state
- State changes propagate to components
- Components retrieve updated data and re-render