Vue.js can be installed via CDN by adding a script tag in the HTML, or via npm with npm install vue
. Using a CDN is good for quick setup, but npm is better for larger projects with a build setup.
The Vue instance is the core of a Vue app, created by new Vue()
. It manages data, methods, and lifecycle hooks. For example:
new Vue({
el: '#app',
data: { message: 'Hello Vue!' }
});
Vue lifecycle hooks are methods that allow you to add code at specific points in a component’s lifecycle. For example, created
runs after an instance is created, and mounted
runs after it’s added to the DOM.
The data
option holds the reactive properties for a Vue instance. In components, data
should be a function that returns an object to avoid shared state across instances.
HTML attributes are bound using v-bind
or the shorthand :
. For example, :href="url"
binds the href
attribute to a dynamic URL.
Vue’s v-model
directive creates two-way data binding between an input and Vue data, syncing user input with app state in real-time.
Directives are special tokens prefixed with v-
that apply reactive behavior to the DOM. Examples: v-if
(conditional rendering), v-for
(looping), and v-bind
(attribute binding).
v-if
conditionally renders an element in the DOM, whereas v-show
toggles the element’s visibility with CSS. v-if
is more performance-efficient but slower in frequent toggling.
v-bind
is used to bind an element’s attribute to a data property. For example, v-bind:src="imageSrc"
dynamically sets the src
attribute of an img
tag.
Event handling is done using v-on
or @
shorthand, binding events like click
to methods. Example: <button @click="greet">Click Me</button>
triggers the greet
method.
Components are reusable blocks of code in Vue. To create one, define an object with template, data, and methods, and register it globally or locally.
Use props to pass data from parent to child, and events (using $emit
) to pass data from child to parent.
Props are custom attributes used to pass data from a parent component to a child component. Define them in the child component to access them.
Use v-model
to create two-way data binding for form inputs, handling user input efficiently by syncing data with form elements.
Computed properties are cached based on dependencies and update only when those dependencies change. They’re used for complex logic or derived data.
Vue Router is the official router for Vue.js, enabling the creation of single-page applications with multiple views by mapping routes to components.
Methods are functions inside the methods
property of a Vue instance or component. They can be used for events or logic. Example:
methods: {
greet() { alert('Hello!'); }
}
Filters transform output text and are typically used for formatting. They can be defined globally or locally. Example:
{{ message | capitalize }}
Vue Mixins are a way to reuse component logic. By defining common functionality in a mixin, it can be included in multiple components. Mixins can include data, methods, lifecycle hooks, etc., and are merged into the component that uses them. Conflicts are resolved by giving priority to the component’s own properties. Example:
const myMixin = { data() { return { sharedData: 'Hello' }; } };
Directives in Vue are special attributes prefixed with v-
, used to apply behaviors to the DOM. Custom directives are created by using Vue.directive
and are ideal for DOM manipulations or reusing custom logic. For example:
Vue.directive('focus', { inserted: function (el) { el.focus(); } });
Vue’s reactivity system is based on data observers that track dependencies and automatically update the DOM when data changes. It uses getters and setters to detect changes, making data reactive. Arrays and objects are reactive by default, but directly adding new properties is not automatically reactive without Vue.set
.
Optimizing a Vue app involves lazy-loading routes, using Vue’s async components, minimizing watchers, and employing computed properties over methods where possible. Additionally, minimizing DOM updates and using the keep-alive
component for caching can improve performance.
Vuex is a state management library for Vue, particularly useful in complex applications where multiple components share data. Vuex centralizes state in a single store, making data management predictable and easy to debug. Use it when app complexity grows and components rely heavily on shared data.
Vue slots allow content distribution in components, enabling components to receive and display custom content passed from their parent components. Named slots provide more customization. Example:
<child>
<template #header>Header Content</template>
</child>
Vue 2’s reactivity system relies on Object.defineProperty
, which can’t detect property additions/deletions in nested objects or arrays. Vue 3 overcomes this by using proxies, which allow full reactivity for deeply nested objects.
The Composition API organizes logic by feature rather than option. This modular approach enhances reusability and readability in complex components, allowing reactive data, computed properties, and lifecycle hooks to be grouped logically, especially useful in large-scale applications.
Vue creates a dependency map for each computed property, re-evaluating only if the tracked dependencies change. Vue 3 further optimizes this with a reactivity tracking system based on dependency collections, reducing unnecessary recalculations.
ref
creates a reactive primitive value or object, making it mutable and tracked by Vue. Unlike reactive
, which tracks objects, ref
is commonly used for individual variables. Both are essential for the Composition API’s reactivity system.
Vue uses garbage collection for unreferenced reactive data, ensuring efficient memory usage. However, event listeners, watchers, or long-lived references should be manually removed or managed, especially in large applications with complex data flows.
Render functions allow programmatically controlling component rendering using JavaScript, offering flexibility for complex UIs or dynamic content generation. They are preferred when templating limitations arise or when you need fine-grained control.
The teleport
feature in Vue 3 allows elements to be rendered outside their component hierarchy in the DOM, useful for modals, tooltips, or overlays. It enables better DOM structure while preserving reactivity and event handling.
Vue’s Composition API includes watch
for deeply tracking reactive data and watchEffect
for running effects based on dependency changes. watchEffect
runs immediately, while watch
is explicitly controlled, useful for conditional logic and asynchronous operations.
Vue 3 offers better TypeScript support with type inference and Composition API. Best practices include defining types for props and state, using defineComponent
, and leveraging TypeScript interfaces for cleaner and safer code.
SSR improves SEO and initial load time but increases server load and complexity. Handling asynchronous data fetching and caching in SSR is more complex, especially with state management and dynamic routing.
ref
is a reactive primitive wrapper, useful for single values, while reactive
deeply tracks objects. ref
is preferred for simple state, and reactive
for nested data structures where granular reactivity is beneficial.
For scalability, modularize Vuex by creating separate modules for different features, namespaces for independent mutations/actions, and use getters for derived state. Vuex plugins and splitting logic into reusable helper functions enhance organization.
provide
and inject
allow dependency injection between ancestor and descendant components, ideal for local state sharing without Vuex. Unlike Vuex’s centralized store, provide/inject
is scoped and lightweight, reducing coupling for isolated state needs.
Suspense
enables asynchronous component loading by showing a fallback UI while waiting for async components or data. It’s used for delayed resources, improving user experience during loading with less boilerplate code than traditional methods.
Hydration issues, like client/server markup mismatch, can be resolved by ensuring identical data on the client and server. Using conditional rendering, defer hydration until data is fully loaded, and checking for specific SSR errors can help avoid inconsistencies.
Use import()
for code splitting, lazy-load only when necessary to reduce initial load time, and strategically use webpackChunkName
for named bundles. Lazy loading in routes and components, along with the Suspense
component, optimizes performance.
Vue 2’s reactivity doesn’t detect direct array mutations (like assigning a new index) due to Object.defineProperty
limitations. In Vue 3, Proxy-based reactivity eliminates this issue by intercepting all operations, but methods like push
or splice
are still preferred.
Use keep-alive
to cache frequently used components, v-once
for static content, and v-memo
in Vue 3 for selective caching. Reduce reactivity scope, minimize watchers, use pagination and debounce for large datasets, and avoid unnecessary re-renders.
Vue 3 allows standalone reactive states outside components with the reactivity
module. This provides reactivity in non-component logic like custom hooks, enabling reactive state management in broader application contexts beyond Vue components.
defineProps
and defineEmits
streamline prop passing and event emitting within setup functions. They improve type inference and readability by defining these properties directly in the setup function, providing a cleaner, TypeScript-compatible syntax.