Vue Interview Master
Curated 200+ Questions to Crack Your Next Vue.js Interview
What is Vue.js?
BeginnerVue.js is a progressive JavaScript framework for building user interfaces. It is designed from the ground up to be incrementally adoptable, and can ea...
Comprehensive Answer:
Vue.js is a progressive JavaScript framework for building user interfaces. It is designed from the ground up to be incrementally adoptable, and can easily scale between a library and a full-featured framework.
What are the core features of Vue?
BeginnerCore features include Reactive Data Binding, Components, Directives (v-if, v-for, etc.), Templates, and the Virtual DOM.
Comprehensive Answer:
Core features include Reactive Data Binding, Components, Directives (v-if, v-for, etc.), Templates, and the Virtual DOM.
What is the Vue Instance?
BeginnerEvery Vue application starts by creating a new Vue instance with the `Vue` function (in Vue 2) or `createApp` (in Vue 3).
Comprehensive Answer:
Every Vue application starts by creating a new Vue instance with the `Vue` function (in Vue 2) or `createApp` (in Vue 3).
Explain Reactive Data Binding in Vue.
BeginnerVue's reactivity system automatically tracks dependency changes and updates the DOM when the underlying data changes, typically using a Model-View-Vie...
Comprehensive Answer:
Vue's reactivity system automatically tracks dependency changes and updates the DOM when the underlying data changes, typically using a Model-View-ViewModel (MVVM) pattern.
What is the difference between Vue 2 and Vue 3?
BeginnerVue 3 introduced the Composition API, better TypeScript support, Fragments, Teleport, and significant performance improvements through a faster Virtua...
Comprehensive Answer:
Vue 3 introduced the Composition API, better TypeScript support, Fragments, Teleport, and significant performance improvements through a faster Virtual DOM and better tree-shaking.
What are Directives in Vue?
BeginnerDirectives are special attributes with the `v-` prefix. They apply special reactive behavior to the rendered DOM (e.g., `v-bind`, `v-model`, `v-on`).
Comprehensive Answer:
Directives are special attributes with the `v-` prefix. They apply special reactive behavior to the rendered DOM (e.g., `v-bind`, `v-model`, `v-on`).
What is `v-model`?
Beginner`v-model` provides two-way data binding on form input, textarea, and select elements. It automatically picks the correct way to update the element bas...
Comprehensive Answer:
`v-model` provides two-way data binding on form input, textarea, and select elements. It automatically picks the correct way to update the element based on the input type.
What is the difference between `v-if` and `v-show`?
Beginner`v-if` is 'real' conditional rendering; it ensures that event listeners and child components inside the conditional block are properly destroyed and r...
Comprehensive Answer:
`v-if` is 'real' conditional rendering; it ensures that event listeners and child components inside the conditional block are properly destroyed and re-created. `v-show` is much simpler—the element is always rendered and remains in the DOM; it simply toggles the `display` CSS property.
What are Components in Vue?
BeginnerComponents are reusable Vue instances with a name. They allow you to divide your UI into independent, reusable pieces.
Comprehensive Answer:
Components are reusable Vue instances with a name. They allow you to divide your UI into independent, reusable pieces.
What are Props in Vue?
BeginnerProps are custom attributes you can register on a component. When a value is passed to a prop attribute, it becomes a property on that component insta...
Comprehensive Answer:
Props are custom attributes you can register on a component. When a value is passed to a prop attribute, it becomes a property on that component instance.
How do you handle events in Vue?
BeginnerYou use the `v-on` directive (shorthand `@`) to listen to DOM events and run some JavaScript when they're triggered.
Comprehensive Answer:
You use the `v-on` directive (shorthand `@`) to listen to DOM events and run some JavaScript when they're triggered.
What is Computed Property?
BeginnerComputed properties are functions used to handle complex logic that depends on other reactive data. They are cached based on their reactive dependenci...
Comprehensive Answer:
Computed properties are functions used to handle complex logic that depends on other reactive data. They are cached based on their reactive dependencies.
What is the difference between Computed and Methods?
BeginnerComputed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its reactive dependencies have chan...
Comprehensive Answer:
Computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its reactive dependencies have changed. In contrast, a method invocation will always run the function whenever a re-render happens.
What are Watchers in Vue?
BeginnerWatchers allow you to perform asynchronous or expensive operations in response to changing data. Use `watch` when you need to perform an action based ...
Comprehensive Answer:
Watchers allow you to perform asynchronous or expensive operations in response to changing data. Use `watch` when you need to perform an action based on a data change.
What is the `key` attribute in `v-for`?
BeginnerThe `key` attribute is used as a hint for Vue's virtual DOM algorithm to identify VNodes when diffing the new list of nodes against the old list. It s...
Comprehensive Answer:
The `key` attribute is used as a hint for Vue's virtual DOM algorithm to identify VNodes when diffing the new list of nodes against the old list. It should be unique and stable.
What are Life Cycle Hooks in Vue?
BeginnerLifecycle hooks are functions that give you the opportunity to add code at specific stages of a component's life (e.g., `created`, `mounted`, `updated...
Comprehensive Answer:
Lifecycle hooks are functions that give you the opportunity to add code at specific stages of a component's life (e.g., `created`, `mounted`, `updated`, `unmounted`).
Explain the `created` hook.
BeginnerThe `created` hook is called synchronously after the instance is created. At this stage, data observation and events are set up, but the mount hasn't ...
Comprehensive Answer:
The `created` hook is called synchronously after the instance is created. At this stage, data observation and events are set up, but the mount hasn't started yet ($el is not available).
Explain the `mounted` hook.
BeginnerThe `mounted` hook is called after the instance has been mounted to the DOM. You can access the DOM elements at this stage.
Comprehensive Answer:
The `mounted` hook is called after the instance has been mounted to the DOM. You can access the DOM elements at this stage.
What is a Template in Vue?
BeginnerA template is an HTML-based syntax that allows you to declaratively bind the rendered DOM to the underlying Vue instance's data.
Comprehensive Answer:
A template is an HTML-based syntax that allows you to declaratively bind the rendered DOM to the underlying Vue instance's data.
What is Single File Component (SFC)?
BeginnerAn SFC is a file with a `.vue` extension that contains the template, logic, and styles of a component in a single file.
Comprehensive Answer:
An SFC is a file with a `.vue` extension that contains the template, logic, and styles of a component in a single file.
What is `v-bind` used for?
Beginner`v-bind` (shorthand `:`) is used to dynamically bind one or more attributes, or a component prop, to an expression.
Comprehensive Answer:
`v-bind` (shorthand `:`) is used to dynamically bind one or more attributes, or a component prop, to an expression.
How to pass data from Child to Parent?
BeginnerChildren communicate to parents by emitting events using `$emit` (Options API) or `emit` (Composition API).
Comprehensive Answer:
Children communicate to parents by emitting events using `$emit` (Options API) or `emit` (Composition API).
What is the Virtual DOM in Vue?
BeginnerThe Virtual DOM is a lightweight JavaScript object representation of the actual DOM. Vue handles updates by comparing changes in the Virtual DOM and o...
Comprehensive Answer:
The Virtual DOM is a lightweight JavaScript object representation of the actual DOM. Vue handles updates by comparing changes in the Virtual DOM and only applying necessary changes to the real DOM.
What are Filters in Vue (Vue 2)?
BeginnerFilters were used to apply common text formatting. Note: Filters are removed in Vue 3; use computed properties or methods instead.
Comprehensive Answer:
Filters were used to apply common text formatting. Note: Filters are removed in Vue 3; use computed properties or methods instead.
What is `v-text`?
Beginner`v-text` updates the element's text content. It is similar to using mustache tags (`{{ }}`).
Comprehensive Answer:
`v-text` updates the element's text content. It is similar to using mustache tags (`{{ }}`).
What is `v-html`?
Beginner`v-html` updates the element's `innerHTML`. Careful with XSS vulnerabilities!
Comprehensive Answer:
`v-html` updates the element's `innerHTML`. Careful with XSS vulnerabilities!
What is `v-once`?
Beginner`v-once` renders the element and component once only. On subsequent re-renders, the element/component and all its children will be treated as static c...
Comprehensive Answer:
`v-once` renders the element and component once only. On subsequent re-renders, the element/component and all its children will be treated as static content and skipped.
What is `v-cloak`?
Beginner`v-cloak` is used to hide un-compiled mustache bindings until the Vue instance is ready.
Comprehensive Answer:
`v-cloak` is used to hide un-compiled mustache bindings until the Vue instance is ready.
How to define global components?
BeginnerIn Vue 3, you use `app.component('my-component', { ... })` on the app instance.
Comprehensive Answer:
In Vue 3, you use `app.component('my-component', { ... })` on the app instance.
What is the use of `ref` in Vue?
Beginner`ref` is used to register a reference to an element or a child component. In Composition API, it's also used to create reactive variables.
Comprehensive Answer:
`ref` is used to register a reference to an element or a child component. In Composition API, it's also used to create reactive variables.
What is the difference between `ref` and `reactive` in Vue 3?
Beginner`ref` can hold primitives or objects and requires `.value` to access/mutate (in JS). `reactive` only holds objects and does not require `.value`.
Comprehensive Answer:
`ref` can hold primitives or objects and requires `.value` to access/mutate (in JS). `reactive` only holds objects and does not require `.value`.
What is the `setup` function in Vue 3?
BeginnerThe `setup` function is the entry point for using the Composition API in components. It's executed before the component is created.
Comprehensive Answer:
The `setup` function is the entry point for using the Composition API in components. It's executed before the component is created.
How to handle forms in Vue?
BeginnerForms are handled using `v-model` for two-way binding and `@submit.prevent` for handling form submission while preventing page reload.
Comprehensive Answer:
Forms are handled using `v-model` for two-way binding and `@submit.prevent` for handling form submission while preventing page reload.
What is `@` in Vue?
Beginner`@` is a shorthand for `v-on`, used for event listening.
Comprehensive Answer:
`@` is a shorthand for `v-on`, used for event listening.
What is `:` in Vue?
Beginner`:` is a shorthand for `v-bind`, used for attribute binding.
Comprehensive Answer:
`:` is a shorthand for `v-bind`, used for attribute binding.
What is `v-pre`?
Beginner`v-pre` skips compilation for this element and all its children. You can use this for displaying raw mustache tags.
Comprehensive Answer:
`v-pre` skips compilation for this element and all its children. You can use this for displaying raw mustache tags.
What is the purpose of `target="_blank"` in Router-Link?
Beginner`router-link` doesn't support `target` directly for internal navigation, but you can use an `<a>` tag or handle it manually if you need to open in a n...
Comprehensive Answer:
`router-link` doesn't support `target` directly for internal navigation, but you can use an `<a>` tag or handle it manually if you need to open in a new tab.
What is `slot` in Vue?
BeginnerSlots are a mechanism for content distribution, allowing parents to pass HTML or components into a child component's template.
Comprehensive Answer:
Slots are a mechanism for content distribution, allowing parents to pass HTML or components into a child component's template.
What is Named Slot?
BeginnerNamed slots allow you to have multiple slots in a single component by assigning a name to the `<slot>` element.
Comprehensive Answer:
Named slots allow you to have multiple slots in a single component by assigning a name to the `<slot>` element.
What is Scoped Slot?
BeginnerScoped slots allow the child component to pass data back to the parent for it to use within the slotted content.
Comprehensive Answer:
Scoped slots allow the child component to pass data back to the parent for it to use within the slotted content.
What is Vue CLI?
BeginnerVue CLI is a standard tooling for Vue.js development, providing project scaffolding, dev server, and build chain.
Comprehensive Answer:
Vue CLI is a standard tooling for Vue.js development, providing project scaffolding, dev server, and build chain.
What is Vite?
BeginnerVite is a modern build tool that provides a faster development experience. It is now the recommended tool for Vue projects instead of Vue CLI.
Comprehensive Answer:
Vite is a modern build tool that provides a faster development experience. It is now the recommended tool for Vue projects instead of Vue CLI.
How to do CSS nesting in Vue SFC?
BeginnerYou can use pre-processors like Sass, Less, or Stylus by adding `lang="scss"` to the `<style>` tag.
Comprehensive Answer:
You can use pre-processors like Sass, Less, or Stylus by adding `lang="scss"` to the `<style>` tag.
What is Scoped CSS?
BeginnerBy adding the `scoped` attribute to a `<style>` tag, the CSS will only apply to elements of the current component.
Comprehensive Answer:
By adding the `scoped` attribute to a `<style>` tag, the CSS will only apply to elements of the current component.
What is `nextTick`?
Beginner`nextTick` allows you to execute code after the next DOM update cycle. Use it when you need to wait for the DOM to update after a data change.
Comprehensive Answer:
`nextTick` allows you to execute code after the next DOM update cycle. Use it when you need to wait for the DOM to update after a data change.
Difference between `v-on:click.stop` and `v-on:click.prevent`?
Beginner.stop` stops event propagation (bubble up). `.prevent` calls `event.preventDefault()` (stops default browser behavior).`
Comprehensive Answer:
.stop` stops event propagation (bubble up). `.prevent` calls `event.preventDefault()` (stops default browser behavior).`
What are Mixins?
BeginnerMixins are a flexible way to distribute reusable functionalities for Vue components (mainly used in Options API; Composition API is preferred in Vue 3...
Comprehensive Answer:
Mixins are a flexible way to distribute reusable functionalities for Vue components (mainly used in Options API; Composition API is preferred in Vue 3).
How to handle 404 routes in Vue Router?
BeginnerBy adding a catch-all route at the end of your routes array: `{ path: '/:pathMatch(.*)*', component: NotFound }`.
Comprehensive Answer:
By adding a catch-all route at the end of your routes array: `{ path: '/:pathMatch(.*)*', component: NotFound }`.
What is the use of `v-bind="$attrs"`?
BeginnerIt allows a component to pass all non-prop attributes down to a child element or component.
Comprehensive Answer:
It allows a component to pass all non-prop attributes down to a child element or component.
What is `defineProps` and `defineEmits` in Vue 3?
BeginnerThese are compiler macros used in `<script setup>` to declare props and emits without needing to import them.
Comprehensive Answer:
These are compiler macros used in `<script setup>` to declare props and emits without needing to import them.
Explain the Composition API in depth.
ExperienceComposition API is a set of APIs that allows us to author Vue components using imported functions instead of declaring options. It provides better log...
Comprehensive Answer:
Composition API is a set of APIs that allows us to author Vue components using imported functions instead of declaring options. It provides better logic reuse, better code organization, and full TypeScript support.
What is Provide / Inject?
ExperienceA pair of options/functions used for deep-level dependency injection, allowing a grandparent to pass data to a grandchild without prop drilling.
Comprehensive Answer:
A pair of options/functions used for deep-level dependency injection, allowing a grandparent to pass data to a grandchild without prop drilling.
What is Teleport?
ExperienceTeleport is a built-in component that allows us to 'teleport' a part of a component's template into a DOM node that exists outside the component hiera...
Comprehensive Answer:
Teleport is a built-in component that allows us to 'teleport' a part of a component's template into a DOM node that exists outside the component hierarchy (e.g., Modals at the end of <body>).
How to use `toRefs` and `toRef`?
Experience`toRefs` converts a reactive object to a plain object where each property is a ref. `toRef` creates a ref for a specific property on a source reactive...
Comprehensive Answer:
`toRefs` converts a reactive object to a plain object where each property is a ref. `toRef` creates a ref for a specific property on a source reactive object.
Explain Vue Router Navigation Guards.
ExperienceNavigation guards are used to guard navigations either by redirecting it or canceling it. Types include Global (beforeEach), Per-route (beforeEnter), ...
Comprehensive Answer:
Navigation guards are used to guard navigations either by redirecting it or canceling it. Types include Global (beforeEach), Per-route (beforeEnter), and In-component (beforeRouteLeave).
What is Pinia?
ExperiencePinia is the recommended store library for Vue apps. It provides a simpler API than Vuex, is fully type-safe, and works well with both Options and Com...
Comprehensive Answer:
Pinia is the recommended store library for Vue apps. It provides a simpler API than Vuex, is fully type-safe, and works well with both Options and Composition APIs.
Difference between Pinia and Vuex?
ExperiencePinia removes Mutations, provides flat store structure (no nested modules), and has better TypeScript inference. Vuex is the older standard.
Comprehensive Answer:
Pinia removes Mutations, provides flat store structure (no nested modules), and has better TypeScript inference. Vuex is the older standard.
Explain Async Components.
ExperienceAsync components are loaded only when they are needed, which helps in code-splitting and reducing the initial bundle size.
Comprehensive Answer:
Async components are loaded only when they are needed, which helps in code-splitting and reducing the initial bundle size.
How to implement custom directives?
ExperienceCustom directives are defined with hooks like `mounted`, `updated`, etc., to perform low-level DOM manipulations.
Comprehensive Answer:
Custom directives are defined with hooks like `mounted`, `updated`, etc., to perform low-level DOM manipulations.
What is `suspense` in Vue 3?
ExperienceSuspense is a built-in component used to coordinate multiple primitive async dependencies (like async components or data fetching) and show a loading ...
Comprehensive Answer:
Suspense is a built-in component used to coordinate multiple primitive async dependencies (like async components or data fetching) and show a loading state.
Explain Plugin system in Vue.
ExperiencePlugins add global-level functionality to Vue. They are usually installed via `app.use(plugin)`.
Comprehensive Answer:
Plugins add global-level functionality to Vue. They are usually installed via `app.use(plugin)`.
How to handle error handling in Vue globally?
ExperienceUsing `app.config.errorHandler` for global error catching or `errorCaptured` hook for component-level catching.
Comprehensive Answer:
Using `app.config.errorHandler` for global error catching or `errorCaptured` hook for component-level catching.
What is logic reuse in Composition API?
ExperienceUsing 'Composables'—functions that encapsulate logic (using refs, computed, hooks) and return state/methods for components to use.
Comprehensive Answer:
Using 'Composables'—functions that encapsulate logic (using refs, computed, hooks) and return state/methods for components to use.
Explain `shallowRef` and `shallowReactive`.
ExperienceThese are versions of `ref` and `reactive` that only track changes at the top level, ignoring nested property changes for performance optimization.
Comprehensive Answer:
These are versions of `ref` and `reactive` that only track changes at the top level, ignoring nested property changes for performance optimization.
What is `watchEffect`?
Experience`watchEffect` immediately runs a function while reactively tracking its dependencies and re-runs it whenever the dependencies change.
Comprehensive Answer:
`watchEffect` immediately runs a function while reactively tracking its dependencies and re-runs it whenever the dependencies change.
Difference between `watch` and `watchEffect`?
Experience`watch` is lazy (runs only when watched source changes), gives access to old/new values, and specifies exactly what to watch. `watchEffect` runs immed...
Comprehensive Answer:
`watch` is lazy (runs only when watched source changes), gives access to old/new values, and specifies exactly what to watch. `watchEffect` runs immediately and tracks all reactive properties used inside it automatically.
How to optimize Vue performance?
ExperienceUsing `v-show` for frequent toggles, `v-once` for static content, `shallowRef` for large immutable datasets, and code splitting via async components.
Comprehensive Answer:
Using `v-show` for frequent toggles, `v-once` for static content, `shallowRef` for large immutable datasets, and code splitting via async components.
What is the purpose of `inheritAttrs: false`?
ExperienceIt prevents the component's root element from automatically inheriting attributes passed to the component, allowing you to manually bind them using `v...
Comprehensive Answer:
It prevents the component's root element from automatically inheriting attributes passed to the component, allowing you to manually bind them using `v-bind="$attrs"`.
Explain HOC (Higher Order Components) in Vue.
ExperienceA pattern where a function takes a component and returns a new one with additional props or logic (less common in Vue than React, but possible).
Comprehensive Answer:
A pattern where a function takes a component and returns a new one with additional props or logic (less common in Vue than React, but possible).
What is Functional Component in Vue?
ExperienceA component that has no state and no instance. In Vue 3, they are just plain functions that return VNodes.
Comprehensive Answer:
A component that has no state and no instance. In Vue 3, they are just plain functions that return VNodes.
How to use `markRaw`?
Experience`markRaw` marks an object so that it will never be converted to a reactive proxy, useful for large non-reactive objects (like third-party maps).
Comprehensive Answer:
`markRaw` marks an object so that it will never be converted to a reactive proxy, useful for large non-reactive objects (like third-party maps).
Explain `computed` getter and setter.
ExperienceComputed properties can have a setter by providing an object with `get` and `set` functions instead of just a function.
Comprehensive Answer:
Computed properties can have a setter by providing an object with `get` and `set` functions instead of just a function.
What is SSR (Server Side Rendering) with Vue?
ExperienceRendering the component tree into an HTML string on the server and sending it to the client for hydration (usually via Nuxt.js).
Comprehensive Answer:
Rendering the component tree into an HTML string on the server and sending it to the client for hydration (usually via Nuxt.js).
Explain `static` vs `dynamic` components.
ExperienceStatic components are declared in the template. Dynamic components use the `<component :is="..." />` syntax to switch between components.
Comprehensive Answer:
Static components are declared in the template. Dynamic components use the `<component :is="..." />` syntax to switch between components.
What is `keep-alive`?
Experience`keep-alive` is a built-in component that caches component instances when switching between them, preserving their state.
Comprehensive Answer:
`keep-alive` is a built-in component that caches component instances when switching between them, preserving their state.
How to handle Cross-Component Communication?
ExperienceProps/Events (Parent-Child), Provide/Inject (Ancestors), Global Store (Pinia/Vuex), or Event Bus (using Mitt library in Vue 3).
Comprehensive Answer:
Props/Events (Parent-Child), Provide/Inject (Ancestors), Global Store (Pinia/Vuex), or Event Bus (using Mitt library in Vue 3).
Explain `v-slot` shorthand.
Experience`v-slot:header` can be shortened to `#header`.
Comprehensive Answer:
`v-slot:header` can be shortened to `#header`.
What is `uncontrolled` component in Vue?
ExperienceA component where the DOM handles the data (using refs to read values) instead of Vue state.
Comprehensive Answer:
A component where the DOM handles the data (using refs to read values) instead of Vue state.
How to use CSS Variables with Vue?
ExperienceVue 3 supports `v-bind` in CSS, allowing you to link CSS properties directly to reactive component variables.
Comprehensive Answer:
Vue 3 supports `v-bind` in CSS, allowing you to link CSS properties directly to reactive component variables.
What is the role of `vue-loader`?
ExperienceIt's a loader for Webpack that allows you to author Vue components in SFC format.
Comprehensive Answer:
It's a loader for Webpack that allows you to author Vue components in SFC format.
Explain `dependency tracking` in Vue.
ExperienceVue uses a `Dep` class to keep track of watchers that depend on a reactive property, triggering them when the property changes.
Comprehensive Answer:
Vue uses a `Dep` class to keep track of watchers that depend on a reactive property, triggering them when the property changes.
How to use `useAttrs` and `useSlots`?
ExperienceThese hooks allow access to attributes and slots inside the `setup` function or `<script setup>`.
Comprehensive Answer:
These hooks allow access to attributes and slots inside the `setup` function or `<script setup>`.
What is `emits` validation?
ExperienceYou can validate the arguments passed to emitted events by defining `emits` as an object with validation functions.
Comprehensive Answer:
You can validate the arguments passed to emitted events by defining `emits` as an object with validation functions.
Explain Vue's `patching` process.
ExperienceThe process of updating the real DOM by comparing the old VNode tree with the new one and applying minimal changes.
Comprehensive Answer:
The process of updating the real DOM by comparing the old VNode tree with the new one and applying minimal changes.
How to implement Middleware in Vue Router?
ExperienceBy using `beforeEach` guard and attaching metadata to routes via the `meta` field.
Comprehensive Answer:
By using `beforeEach` guard and attaching metadata to routes via the `meta` field.
What is `defineExpose`?
ExperienceIn `<script setup>`, components are closed by default. `defineExpose` is used to explicitly declare which properties/methods are available when the pa...
Comprehensive Answer:
In `<script setup>`, components are closed by default. `defineExpose` is used to explicitly declare which properties/methods are available when the parent uses a `ref` on the component.
How to use `provide/inject` with Reactivity?
ExperiencePass a `ref` or a `reactive` object to `provide` to ensure the injected value stays reactive in child components.
Comprehensive Answer:
Pass a `ref` or a `reactive` object to `provide` to ensure the injected value stays reactive in child components.
Explain `dynamic` route matching.
ExperienceRoutes with params like `/user/:id`, where `id` can be accessed via `route.params.id`.
Comprehensive Answer:
Routes with params like `/user/:id`, where `id` can be accessed via `route.params.id`.
What is `v-on` native modifier (Vue 2)?
Experience`.native` was used to listen to native DOM events on component root. In Vue 3, this is removed; all events not declared in `emits` are treated as nati...
Comprehensive Answer:
`.native` was used to listen to native DOM events on component root. In Vue 3, this is removed; all events not declared in `emits` are treated as native events.
How to implement Breadcrumbs with Vue Router?
ExperienceBy iterating through `route.matched` array to get the hierarchy of nested routes.
Comprehensive Answer:
By iterating through `route.matched` array to get the hierarchy of nested routes.
What is `vue-cli-service`?
ExperienceAn executable that provides internal build commands for Vue CLI projects.
Comprehensive Answer:
An executable that provides internal build commands for Vue CLI projects.
Difference between `export default` and `defineComponent`?
Experience`defineComponent` is a type helper for better TypeScript support, whereas `export default` is standard JS.
Comprehensive Answer:
`defineComponent` is a type helper for better TypeScript support, whereas `export default` is standard JS.
How to use `onBeforeRouteUpdate` hook?
ExperienceUsed to handle cases where the route changes but the component is reused (e.g., from `/user/1` to `/user/2`).
Comprehensive Answer:
Used to handle cases where the route changes but the component is reused (e.g., from `/user/1` to `/user/2`).
What is `transition-group`?
ExperienceUsed for animating transitions of multiple elements (e.g., items in a list) using `v-for`.
Comprehensive Answer:
Used for animating transitions of multiple elements (e.g., items in a list) using `v-for`.
How to handle API call cancellation on component unmount?
ExperienceUsing `AbortController` and calling `.abort()` in the `onUnmounted` hook.
Comprehensive Answer:
Using `AbortController` and calling `.abort()` in the `onUnmounted` hook.
Explain `shallowSfc` concept.
ExperienceActually not a standard term, but usually refers to testing only the current component without its children.
Comprehensive Answer:
Actually not a standard term, but usually refers to testing only the current component without its children.
How to use `v-memo` (Vue 3.2+)?
ExperienceSpeeds up rendering for large lists by skipping re-renders if a specific dependency array hasn't changed.
Comprehensive Answer:
Speeds up rendering for large lists by skipping re-renders if a specific dependency array hasn't changed.
What is `custom elements` support in Vue?
ExperienceVue allows compiling components into standard Web Components using `defineCustomElement`.
Comprehensive Answer:
Vue allows compiling components into standard Web Components using `defineCustomElement`.
Explain `Hydration Error` in Vue.
ExperienceOccurs in SSR when the server-rendered HTML doesn't match the client-side initial render (e.g., due to random numbers or dates).
Comprehensive Answer:
Occurs in SSR when the server-rendered HTML doesn't match the client-side initial render (e.g., due to random numbers or dates).
How to use `useCssModule` hook?
ExperienceUsed to access CSS Module classes in the Composition API.
Comprehensive Answer:
Used to access CSS Module classes in the Composition API.
How does Vue's Reactivity System work under the hood?
AdvancedVue 3 uses `Proxy` to intercept property access and mutation. When a property is accessed, a dependency is 'tracked'. When mutated, the dependencies a...
Comprehensive Answer:
Vue 3 uses `Proxy` to intercept property access and mutation. When a property is accessed, a dependency is 'tracked'. When mutated, the dependencies are 'triggered' to re-run.
Explain Virtual DOM's `Diffing Algorithm` in Vue 3.
AdvancedVue 3 uses a 'Blocked' Virtual DOM which analyzes templates at build time to mark dynamic parts. During patching, it only visits the dynamic nodes, si...
Comprehensive Answer:
Vue 3 uses a 'Blocked' Virtual DOM which analyzes templates at build time to mark dynamic parts. During patching, it only visits the dynamic nodes, significantly improving performance ('compiler-informed virtualization').
Deep Dive: Proxy vs Object.defineProperty.
Advanced`Proxy` can detect property addition/deletion and array index changes, which `defineProperty` couldn't. `Proxy` is also faster and doesn't require pre...
Comprehensive Answer:
`Proxy` can detect property addition/deletion and array index changes, which `defineProperty` couldn't. `Proxy` is also faster and doesn't require pre-traversing the object.
Explain Custom Renderers in Vue 3.
AdvancedUsing `@vue/runtime-core`, you can create custom renderers for non-DOM environments like Canvas, Terminal, or Mobile (e.g., Vue Native, TresJS).
Comprehensive Answer:
Using `@vue/runtime-core`, you can create custom renderers for non-DOM environments like Canvas, Terminal, or Mobile (e.g., Vue Native, TresJS).
What is Compiler-Informed Fast Path?
AdvancedVue 3 compiler analyzes the template and adds 'Patch Flags' to VNodes (e.g., TEXT, CLASS). The runtime then uses these flags to skip unnecessary check...
Comprehensive Answer:
Vue 3 compiler analyzes the template and adds 'Patch Flags' to VNodes (e.g., TEXT, CLASS). The runtime then uses these flags to skip unnecessary checks.
How to implement Micro-frontends with Vue?
AdvancedUsing Webpack Module Federation, single-spa, or Vite's module-based approach with iframes or shared runtimes.
Comprehensive Answer:
Using Webpack Module Federation, single-spa, or Vite's module-based approach with iframes or shared runtimes.
Explain `Effect Scope` API.
AdvancedAllows creating a scope that can collect reactive effects (like watchers and computed) and dispose of them all at once, useful for build-time abstract...
Comprehensive Answer:
Allows creating a scope that can collect reactive effects (like watchers and computed) and dispose of them all at once, useful for build-time abstractions or complex composables.
What is the difference between `Runtime-Only` vs `Runtime + Compiler`?
AdvancedRuntime-only is smaller but requires pre-compilation of templates. Runtime+Compiler allows compiling templates in the browser but adds ~10KB overhead.
Comprehensive Answer:
Runtime-only is smaller but requires pre-compilation of templates. Runtime+Compiler allows compiling templates in the browser but adds ~10KB overhead.
Explain `Tree-shaking` in Vue 3.
AdvancedVue 3 is written in a way that if you don't use a feature (like `Teleport` or `v-model`), it won't be included in the final production bundle.
Comprehensive Answer:
Vue 3 is written in a way that if you don't use a feature (like `Teleport` or `v-model`), it won't be included in the final production bundle.
What is `Hoisting` in Vue templates?
AdvancedThe compiler hoists static VNodes outside of the render function so they are created only once and reused across renders.
Comprehensive Answer:
The compiler hoists static VNodes outside of the render function so they are created only once and reused across renders.
How does `Transition` work internally?
AdvancedVue detects CSS transitions/animations on the element and automatically adds/removes CSS classes (`v-enter-from`, `v-enter-to`, etc.) at the right tim...
Comprehensive Answer:
Vue detects CSS transitions/animations on the element and automatically adds/removes CSS classes (`v-enter-from`, `v-enter-to`, etc.) at the right time.
Explain `Reactive` object unwrapping.
AdvancedRefs are automatically unwrapped when accessed as properties of a reactive object or in the template, so you don't need `.value`.
Comprehensive Answer:
Refs are automatically unwrapped when accessed as properties of a reactive object or in the template, so you don't need `.value`.
Deep Dive: Scoped CSS implementation.
AdvancedVue adds a unique `data-v-xxxx` attribute to elements and modifies CSS selectors to target that attribute (`.my-class[data-v-xxxx]`).
Comprehensive Answer:
Vue adds a unique `data-v-xxxx` attribute to elements and modifies CSS selectors to target that attribute (`.my-class[data-v-xxxx]`).
How to build a Design System with Vue?
AdvancedCreating a package of atomic components using SFCs, documenting with Storybook, and distributing via NPM with types.
Comprehensive Answer:
Creating a package of atomic components using SFCs, documenting with Storybook, and distributing via NPM with types.
Explain `Vite`'s Hot Module Replacement (HMR).
AdvancedVite uses ES Modules in development. When a file changes, it only replaces the module in the browser without reloading the page, preserving state.
Comprehensive Answer:
Vite uses ES Modules in development. When a file changes, it only replaces the module in the browser without reloading the page, preserving state.
What is `Static Site Generation` (SSG) with Nuxt?
AdvancedGenerating every route of your application as a static HTML file at build time for maximum speed and SEO.
Comprehensive Answer:
Generating every route of your application as a static HTML file at build time for maximum speed and SEO.
How to handle large scale state with Pinia?
AdvancedBy modularizing stores, using getters for derived state, and leveraging Pinia's subscription API for side effects.
Comprehensive Answer:
By modularizing stores, using getters for derived state, and leveraging Pinia's subscription API for side effects.
Explain `Functional` components performance.
AdvancedIn Vue 2, functional components were significantly faster. In Vue 3, regular components are so fast that functional components offer minimal benefit.
Comprehensive Answer:
In Vue 2, functional components were significantly faster. In Vue 3, regular components are so fast that functional components offer minimal benefit.
How to use `useAsyncData` and `useFetch` in Nuxt 3?
AdvancedThese are composables designed for Universal data fetching, ensuring data is fetched once on the server and hydrated on the client.
Comprehensive Answer:
These are composables designed for Universal data fetching, ensuring data is fetched once on the server and hydrated on the client.
What is `Reactive Transform` (Experimental)?
AdvancedA compiler-time transformation that allowed using `$ref` instead of `ref` to avoid `.value` (deprecated/removed in later versions in favor of standard...
Comprehensive Answer:
A compiler-time transformation that allowed using `$ref` instead of `ref` to avoid `.value` (deprecated/removed in later versions in favor of standard refs).
Security: `v-html` and CSRF protection.
AdvancedAlways sanitize HTML using DOMPurify before using `v-html`. Ensure your API uses CSRF tokens if it relies on cookie-based auth.
Comprehensive Answer:
Always sanitize HTML using DOMPurify before using `v-html`. Ensure your API uses CSRF tokens if it relies on cookie-based auth.
How to implement `Custom Event Modifiers`?
AdvancedActually Vue doesn't officially support custom modifiers, but you can wrap logic in a function or handle it in a custom directive.
Comprehensive Answer:
Actually Vue doesn't officially support custom modifiers, but you can wrap logic in a function or handle it in a custom directive.
Deep Dive: `v-model` on custom components.
AdvancedBy default uses `modelValue` prop and `update:modelValue` event. Can be customized with different prop/event names in Vue 3.
Comprehensive Answer:
By default uses `modelValue` prop and `update:modelValue` event. Can be customized with different prop/event names in Vue 3.
How to use `Web Workers` with Vue Composition API?
AdvancedBy offloading heavy logic into a worker file and communicating via `postMessage` encapsulated within a Composable.
Comprehensive Answer:
By offloading heavy logic into a worker file and communicating via `postMessage` encapsulated within a Composable.
Explain `Module Federation` with Vite.
AdvancedUsing the `vite-plugin-federation` to share modules between independent builds at runtime.
Comprehensive Answer:
Using the `vite-plugin-federation` to share modules between independent builds at runtime.
Architecture: `Feature Slicing Design` in Vue.
AdvancedOrganizing the project into Layers (app, processes, pages, features, entities, shared) to improve maintainability.
Comprehensive Answer:
Organizing the project into Layers (app, processes, pages, features, entities, shared) to improve maintainability.
How to unit test `Composables`?
AdvancedBy testing the logic in isolation, occasionally using a dummy component if the composable relies on lifecycle hooks.
Comprehensive Answer:
By testing the logic in isolation, occasionally using a dummy component if the composable relies on lifecycle hooks.
Explain `Hydration Error` debugging.
AdvancedChecking for browser-specific APIs (window, document) used during the first render, or mismatched data between sever/client.
Comprehensive Answer:
Checking for browser-specific APIs (window, document) used during the first render, or mismatched data between sever/client.
How to implement `Role Based Access Control` (RBAC) in Vue?
AdvancedUsing Vue Router Meta fields and a global `beforeEach` guard to check user roles against required permissions.
Comprehensive Answer:
Using Vue Router Meta fields and a global `beforeEach` guard to check user roles against required permissions.
Deep Dive: `Suspense` and data fetching patterns.
AdvancedCoordinating top-level loading states by making `setup` async or using `await` in `<script setup>`.
Comprehensive Answer:
Coordinating top-level loading states by making `setup` async or using `await` in `<script setup>`.
What is `Static Content Hoisting`?
AdvancedCompiler optimization where static HTML parts are stringified and created via `innerHTML` for massive speedups in heavy static templates.
Comprehensive Answer:
Compiler optimization where static HTML parts are stringified and created via `innerHTML` for massive speedups in heavy static templates.
How to use `provide/inject` for state management?
AdvancedAs a 'light' alternative to Pinia for feature-scoped or module-scoped state sharing.
Comprehensive Answer:
As a 'light' alternative to Pinia for feature-scoped or module-scoped state sharing.
What is `Patch Flag` enumerate?
AdvancedIntegers representing different types of dynamic content (e.g., 1 for text, 2 for class) used by the patcher.
Comprehensive Answer:
Integers representing different types of dynamic content (e.g., 1 for text, 2 for class) used by the patcher.
How to implement `Double-Click` directive?
AdvancedA custom directive that tracks time between clicks and triggers a callback if the interval is small.
Comprehensive Answer:
A custom directive that tracks time between clicks and triggers a callback if the interval is small.
Explain `Transition` vs `TransitionGroup` hooks.
Advanced`Transition` is for a single element. `TransitionGroup` is for multiple elements, requiring a `tag` prop and unique `key` for each item.
Comprehensive Answer:
`Transition` is for a single element. `TransitionGroup` is for multiple elements, requiring a `tag` prop and unique `key` for each item.
How to scale Vue applications to millions of users?
AdvancedUsing SSR/SSG for fast initial load, aggressive caching, CDN distribution, and optimized bundle fragmentation.
Comprehensive Answer:
Using SSR/SSG for fast initial load, aggressive caching, CDN distribution, and optimized bundle fragmentation.
What is `unmount` vs `destroy`?
Advanced`destroy` was used in Vue 2; it was renamed to `unmount` in Vue 3 to better match the lifecycle of many modern frameworks.
Comprehensive Answer:
`destroy` was used in Vue 2; it was renamed to `unmount` in Vue 3 to better match the lifecycle of many modern frameworks.
How to use `@vue/compiler-sfc` directly?
AdvancedUsed by build tools to parse, template-compile, and style-compile SFC files programmatically.
Comprehensive Answer:
Used by build tools to parse, template-compile, and style-compile SFC files programmatically.
Explain `VNode` structure.
AdvancedAn object with `type`, `props`, `children`, `key`, `el`, and other management properties.
Comprehensive Answer:
An object with `type`, `props`, `children`, `key`, `el`, and other management properties.
How to handle `Reactivity Leak`?
AdvancedEnsuring watchers and event listeners are properly stopped/removed when no longer needed (Vue 3 handles most of this automatically in `onUnmounted`).
Comprehensive Answer:
Ensuring watchers and event listeners are properly stopped/removed when no longer needed (Vue 3 handles most of this automatically in `onUnmounted`).
What is `Slots` implementation in VNode?
AdvancedSlots are passed as an object of functions (`children` property in VNode) that return arrays of VNodes.
Comprehensive Answer:
Slots are passed as an object of functions (`children` property in VNode) that return arrays of VNodes.
Deep Dive: `v-memo` vs `v-once`.
Advanced`v-once` never updates. `v-memo` only updates when its dependencies change, allowing partial reactivity.
Comprehensive Answer:
`v-once` never updates. `v-memo` only updates when its dependencies change, allowing partial reactivity.
How to use `defineComponent` with Generics?
AdvancedThrough complex TypeScript typings or using the `<script setup lang="ts" generic="T">` feature in Vue 3.3+.
Comprehensive Answer:
Through complex TypeScript typings or using the `<script setup lang="ts" generic="T">` feature in Vue 3.3+.
Explain `Plugin` vs `Composable` usage.
AdvancedPlugins are for global configuration or app-wide services. Composables are for shared logic and state between components.
Comprehensive Answer:
Plugins are for global configuration or app-wide services. Composables are for shared logic and state between components.
How to manage `Third-party Map` (Google/Leaflet) in Vue?
AdvancedUse `ref` to target a container, initialize in `mounted`, and use `markRaw` to prevent Vue from trying to make the map object reactive.
Comprehensive Answer:
Use `ref` to target a container, initialize in `mounted`, and use `markRaw` to prevent Vue from trying to make the map object reactive.
What is `defineOptions`?
AdvancedA macro in Vue 3.3+ to define component options (like `name`, `inheritAttrs`) directly inside `<script setup>`.
Comprehensive Answer:
A macro in Vue 3.3+ to define component options (like `name`, `inheritAttrs`) directly inside `<script setup>`.
Explain `Slots` type checking in Vue 3.3.
AdvancedUsing `@slots` or `defineSlots` to provide type safety for scoped slots in external component usage.
Comprehensive Answer:
Using `@slots` or `defineSlots` to provide type safety for scoped slots in external component usage.
How to handle `Large Form` partial validation?
AdvancedUsing libraries like Vuelidate or VeeValidate which allow validating specific fields or groups of fields.
Comprehensive Answer:
Using libraries like Vuelidate or VeeValidate which allow validating specific fields or groups of fields.
Deep Dive: `Vue Router` History Modes.
AdvancedHTML5 (`createWebHistory`), Hash (`createWebHashHistory`), and Memory (`createMemoryHistory`) modes and how each interacts with the server.
Comprehensive Answer:
HTML5 (`createWebHistory`), Hash (`createWebHashHistory`), and Memory (`createMemoryHistory`) modes and how each interacts with the server.
What is the future of Vue (Vapor Mode)?
AdvancedVapor mode is an upcoming compiler that generates zero-virtual-DOM code, resulting in even smaller and faster apps.
Comprehensive Answer:
Vapor mode is an upcoming compiler that generates zero-virtual-DOM code, resulting in even smaller and faster apps.
How to implement a `useFetch` composable?
ExperienceCreate a function that returns reactive `data`, `error`, and `loading` states.
Comprehensive Answer:
Create a function that returns reactive `data`, `error`, and `loading` states.
Vue Snippet:
export function useFetch(url) {
const data = ref(null);
const error = ref(null);
const loading = ref(true);
fetch(url)
.then(res => res.json())
.then(json => (data.value = json))
.catch(err => (error.value = err))
.finally(() => (loading.value = false));
return { data, error, loading };
}Create a simple Toggle button with Vue 3.
BeginnerUse a simple ref and toggle it with a click.
Comprehensive Answer:
Use a simple ref and toggle it with a click.
Vue Snippet:
<script setup>
const active = ref(false);
</script>
<button @click="active = !active">
{{ active ? 'ON' : 'OFF' }}
</button>How to implement a Search Filter on a list?
BeginnerUse a computed property that filters the array based on a query ref.
Comprehensive Answer:
Use a computed property that filters the array based on a query ref.
Vue Snippet:
const query = ref('');
const filtered = computed(() => {
return items.value.filter(item => item.name.includes(query.value));
});Implement a Countdown Timer.
ExperienceUse `setInterval` and `onUnmounted` for cleanup.
Comprehensive Answer:
Use `setInterval` and `onUnmounted` for cleanup.
Vue Snippet:
const count = ref(60);
let timer;
onMounted(() => {
timer = setInterval(() => count.value--, 1000);
});
onUnmounted(() => clearInterval(timer));How to create a `useLocalStorage` composable?
ExperienceA function that syncs a reactive ref with a localStorage key.
Comprehensive Answer:
A function that syncs a reactive ref with a localStorage key.
Vue Snippet:
export function useLocalStorage(key, val) {
const storage = ref(JSON.parse(localStorage.getItem(key)) || val);
watchEffect(() => localStorage.setItem(key, JSON.stringify(storage.value)));
return storage;
}Implement a deep copy in JavaScript.
BeginnerUse JSON parse/stringify for simple objects or structuredClone for modern browsers.
Comprehensive Answer:
Use JSON parse/stringify for simple objects or structuredClone for modern browsers.
Vue Snippet:
const copy = obj => JSON.parse(JSON.stringify(obj));How to debounce a search input in Vue?
ExperienceWatch the input and use a timeout.
Comprehensive Answer:
Watch the input and use a timeout.
Vue Snippet:
watch(input, (val) => {
clearTimeout(timeout);
timeout = setTimeout(() => search(val), 500);
});Create a `useMouse` composable.
BeginnerTrack mouse coordinates globally.
Comprehensive Answer:
Track mouse coordinates globally.
Vue Snippet:
export function useMouse() {
const x = ref(0);
const y = ref(0);
const update = e => { x.value = e.pageX; y.value = e.pageY; };
onMounted(() => window.addEventListener('mousemove', update));
onUnmounted(() => window.removeEventListener('mousemove', update));
return { x, y };
}Check if a string is a palindrome.
BeginnerReverse and compare.
Comprehensive Answer:
Reverse and compare.
Vue Snippet:
const isPal = s => s === s.split('').reverse().join('');Implement a simple `v-focus` directive.
BeginnerFocus the element when it is mounted.
Comprehensive Answer:
Focus the element when it is mounted.
Vue Snippet:
const vFocus = {
mounted: (el) => el.focus()
};How to handle multiple models with `v-model` in Vue 3?
ExperienceUse arguments like `v-model:title` and `v-model:content`.
Comprehensive Answer:
Use arguments like `v-model:title` and `v-model:content`.
Vue Snippet:
defineProps(['title', 'content']);
const emit = defineEmits(['update:title', 'update:content']);Flatten a nested array without .flat().
ExperienceUse recursion with reduce.
Comprehensive Answer:
Use recursion with reduce.
Vue Snippet:
const flatten = arr => arr.reduce((acc, val) =>
Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []);Sum of all even numbers in an array.
BeginnerFilter and then reduce.
Comprehensive Answer:
Filter and then reduce.
Vue Snippet:
const sumEven = arr => arr.filter(n => n % 2 === 0).reduce((a, b) => a + b, 0);How to use `Suspense` and handle errors?
AdvancedWrap `Suspense` with an `onErrorCaptured` component.
Comprehensive Answer:
Wrap `Suspense` with an `onErrorCaptured` component.
Vue Snippet:
<Suspense>
<AsyncComponent />
<template #fallback>Loading...</template>
</Suspense>Remove duplicates from an array.
BeginnerUse a Set.
Comprehensive Answer:
Use a Set.
Vue Snippet:
const unique = arr => [...new Set(arr)];Implement a generic `useToggle` hook.
BeginnerA function that returns a boolean and a toggle function.
Comprehensive Answer:
A function that returns a boolean and a toggle function.
Vue Snippet:
export function useToggle(init = false) {
const state = ref(init);
const toggle = () => (state.value = !state.value);
return [state, toggle];
}How to use `nextTick` for DOM access?
BeginnerWait for DOM updates after state changes.
Comprehensive Answer:
Wait for DOM updates after state changes.
Vue Snippet:
count.value++;
await nextTick();
console.log(el.value.textContent);Capitalize the first letter of each word.
BeginnerMap through words and capitalize.
Comprehensive Answer:
Map through words and capitalize.
Vue Snippet:
const cap = s => s.split(' ').map(w => w[0].toUpperCase() + w.slice(1)).join(' ');Implement Fibonacci sequence.
BeginnerStandard recursive or iterative approach.
Comprehensive Answer:
Standard recursive or iterative approach.
Vue Snippet:
const fib = n => n <= 1 ? n : fib(n-1) + fib(n-2);Find the longest word in a string.
BeginnerSplit and reduce to find max length.
Comprehensive Answer:
Split and reduce to find max length.
Vue Snippet:
const longest = s => s.split(' ').reduce((a, b) => b.length > a.length ? b : a);How to create a Custom SVG Loader component?
BeginnerPass SVG paths as props.
Comprehensive Answer:
Pass SVG paths as props.
Vue Snippet:
<template>
<svg><path :d="iconPath" /></svg>
</template>Implement a Drag and Drop logic (Basic).
AdvancedUse `draggable` attribute and `dragstart/drop` events.
Comprehensive Answer:
Use `draggable` attribute and `dragstart/drop` events.
Vue Snippet:
<div draggable="true" @dragstart="handleDrag">Check if two objects are equal (Deep Equality).
AdvancedRecursive comparison of keys and values.
Comprehensive Answer:
Recursive comparison of keys and values.
Vue Snippet:
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);How to use `toRef` on a reactive object property?
BeginnerLink a single property to a new ref.
Comprehensive Answer:
Link a single property to a new ref.
Vue Snippet:
const name = toRef(user, 'name');Implement an Infinite Scroll (Intersection Observer).
AdvancedObserve a sentinel element at the bottom of the list.
Comprehensive Answer:
Observe a sentinel element at the bottom of the list.
Vue Snippet:
new IntersectionObserver(([e]) => {
if(e.isIntersecting) loadMore();
}).observe(sentinel.value);Find the maximum number in an array.
BeginnerUse `Math.max` with spread.
Comprehensive Answer:
Use `Math.max` with spread.
Vue Snippet:
const max = arr => Math.max(...arr);Create a simple Pinia store.
ExperienceDefine state, getters, and actions.
Comprehensive Answer:
Define state, getters, and actions.
Vue Snippet:
export const useStore = defineStore('main', {
state: () => ({ count: 0 }),
actions: { increment() { this.count++ } }
});How to handle file upload in Vue?
BeginnerAccess files from a file input change event.
Comprehensive Answer:
Access files from a file input change event.
Vue Snippet:
const onFile = e => { const file = e.target.files[0]; };Implement a simple `v-ripple` directive effect.
AdvancedClick listener that adds a temporary expanding circle to the DOM.
Comprehensive Answer:
Click listener that adds a temporary expanding circle to the DOM.
Vue Snippet:
mounted(el) { el.onclick = e => { ... } }Calculate the average of an array of numbers.
BeginnerSum divided by length.
Comprehensive Answer:
Sum divided by length.
Vue Snippet:
const avg = arr => arr.reduce((a, b) => a + b, 0) / arr.length;How to use `useAsyncState` in VueUse?
ExperienceHandle non-blocking data fetching easily.
Comprehensive Answer:
Handle non-blocking data fetching easily.
Vue Snippet:
const { state, isReady } = useAsyncState(fetchData());Generate a random Hex color.
BeginnerRandom number to hex string.
Comprehensive Answer:
Random number to hex string.
Vue Snippet:
const color = () => '#' + Math.floor(Math.random()*16777215).toString(16);Reverse a number in JS.
BeginnerConvert to string, reverse, and back to number.
Comprehensive Answer:
Convert to string, reverse, and back to number.
Vue Snippet:
const rev = n => parseFloat(n.toString().split('').reverse().join('')) * Math.sign(n);How to use `teleport` for a notification toast?
BeginnerTeleport to a dedicated container outside the app overflow.
Comprehensive Answer:
Teleport to a dedicated container outside the app overflow.
Vue Snippet:
<Teleport to="body"><Toast /></Teleport>Implement a simple `Pub/Sub` pattern in JS.
ExperienceAn object with events and subscribe/publish methods.
Comprehensive Answer:
An object with events and subscribe/publish methods.
Vue Snippet:
const bus = { events: {}, emit(n, d) { ... }, on(n, f) { ... } };Find the missing number in an array (1-100).
ExperienceSubtract actual sum from expected sum.
Comprehensive Answer:
Subtract actual sum from expected sum.
Vue Snippet:
const missing = arr => (100 * 101 / 2) - arr.reduce((a,b)=>a+b);How to use `provide/inject` for a Theme Switcher?
ExperienceProvide the theme ref at the top and inject it in components.
Comprehensive Answer:
Provide the theme ref at the top and inject it in components.
Vue Snippet:
provide('theme', themeRef);Implement a simple `v-lazy` image loader.
ExperienceUse Intersection Observer to swap data-src to src.
Comprehensive Answer:
Use Intersection Observer to swap data-src to src.
Vue Snippet:
mounted(el) { observer.observe(el); }FizzBuzz problem implementation.
BeginnerModulo for 3, 5, or both.
Comprehensive Answer:
Modulo for 3, 5, or both.
Vue Snippet:
for(let i=1;i<=15;i++) console.log((i%3?'':'Fizz')+(i%5?'':'Buzz')||i);Count vowels in a string.
BeginnerRegex match length.
Comprehensive Answer:
Regex match length.
Vue Snippet:
const count = s => (s.match(/[aeiou]/gi) || []).length;How to use `AbortController` in `fetch`?
ExperiencePass the signal to fetch and call abort on unmount.
Comprehensive Answer:
Pass the signal to fetch and call abort on unmount.
Vue Snippet:
const ctrl = new AbortController(); fetch(u, { signal: ctrl.signal });Check if an object is empty.
BeginnerObject.keys length check.
Comprehensive Answer:
Object.keys length check.
Vue Snippet:
const empty = o => Object.keys(o).length === 0;Implement a sorting function for a table.
BeginnerRe-order the array based on a key and direction.
Comprehensive Answer:
Re-order the array based on a key and direction.
Vue Snippet:
const sort = (key) => items.value.sort((a,b) => a[key] > b[key] ? 1 : -1);How to use `useVModel` from VueUse?
ExperienceEasily sync a prop with a local ref for `v-model` binding.
Comprehensive Answer:
Easily sync a prop with a local ref for `v-model` binding.
Vue Snippet:
const data = useVModel(props, 'modelValue', emit);Shuffle an array randomly.
BeginnerFisher-Yates shuffle algorithm.
Comprehensive Answer:
Fisher-Yates shuffle algorithm.
Vue Snippet:
const shuffle = arr => arr.sort(() => Math.random() - 0.5);Detect prime numbers.
BeginnerCheck divisibility up to sqrt(n).
Comprehensive Answer:
Check divisibility up to sqrt(n).
Vue Snippet:
const isPrime = n => { for(let i=2; i<=Math.sqrt(n); i++) if(n%i===0) return false; return n > 1; };How to create a `useWindowResize` composable?
BeginnerWatch window resize event and update width/height refs.
Comprehensive Answer:
Watch window resize event and update width/height refs.
Vue Snippet:
window.onresize = () => { w.value = window.innerWidth; };Convert Snake Case to Camel Case in JS.
BeginnerRegex string replacement.
Comprehensive Answer:
Regex string replacement.
Vue Snippet:
const toCamel = s => s.replace(/_([a-z])/g, m => m[1].toUpperCase());Implement a simple `v-tooltip` directive (title based).
ExperienceCreate and position a floating div on mouseover.
Comprehensive Answer:
Create and position a floating div on mouseover.
Vue Snippet:
mounted(el) { el.onmouseenter = ... }How to use `defineExpose` for a Modal component?
ExperienceExpose 'open' and 'close' methods to the parent.
Comprehensive Answer:
Expose 'open' and 'close' methods to the parent.
Vue Snippet:
defineExpose({ open: () => (show.value = true) });