Vue.js is a progressive, lightweight, and flexible JavaScript framework used for building modern web applications, making it an excellent choice for both single-page applications (SPAs) and complex web interfaces. Vue.js provides powerful features like the reactivity system, component-based architecture, Vue Router, Vuex (or Pinia) for state management, and server-side rendering (SSR) with Nuxt.js.
Beginners Level Questions
1. What is Vue.js?
Vue.js is an open-source, progressive JavaScript framework used to build user interfaces (UIs) and single-page applications (SPAs). It is component-based, focuses on the view layer, and provides a reactive data-binding system, making it easy to build interactive, scalable, and maintainable web applications.
2. What is a Single-Page Application?
A Single Page Applications (SPAs) is a web application that loads a single HTML page once and dynamically updates its content without reloading the entire page. It uses JavaScript to communicate with the server (via APIs) and update the UI, providing a faster and smoother user experience.
3. What is a component in Vue.js? How can we create a component?
A component in Vue.js is a reusable, self-contained piece of the user interface. Components help build large applications by dividing the UI into smaller, reusable, and maintainable parts.
Step 1: Create a component (MyComponent.vue)
<template>
<h1>Hello, {{ message }}</h1>
</template>
<script>
export default {
name: "MyComponent",
data() {
return {
message: "Vue.js",
};
},
};
</script>
<style scoped>
h1 {
color: blue;
}
</style>
Step 2: Register and use the component (Vue 3)
import { createApp } from "vue";
import App from "./App.vue";
import MyComponent from "./MyComponent.vue";
const app = createApp(App);
app.component("MyComponent", MyComponent);
app.mount("#app");
Step 3: Use the component
<template>
<MyComponent />
</template>
4. What are Props in Vue.js?
Props are read-only custom attributes used to pass data from a parent component to a child component. They improve component reusability by allowing child components to receive dynamic data from their parent.
Child Component (ChildComponent.vue)
<script>
export default {
props: {
message: String,
},
};
</script>
Parent Component
<template>
<ChildComponent message="Hello Vue!" />
</template>
5. What is the difference between one-way data binding and two-way data binding in Vue.js?
One-Way Data Binding | Two-Way Data Binding |
|---|---|
Data flows from the model to the view only. | Data flows between the model and the view. |
Changes in the model update the view, but changes in the view do not update the model automatically. | Changes in either the model or the view are automatically synchronized. |
Uses v-bind (or : shorthand). | Uses v-model. |
Commonly used for displaying data or binding element attributes. | Commonly used with form elements such as <input>, <textarea>, and <select>. |
6. What is a Vue.js Router?
Vue Router is the official routing library for Vue.js. It enables navigation between different views in a Single-Page Application (SPA) by mapping URL paths to Vue components without reloading the page.
- Maps URL routes to Vue components.
- Supports dynamic routes and nested routes.
- Provides navigation guards for authentication and route protection.
- Uses the browser's History API for seamless navigation.
7. What is a Vue instance? How can we create a Vue instance?
A Vue instance (or application instance in Vue 3) is the entry point of a Vue application. It manages the application's data, components, and lifecycle, and mounts the application to a DOM element.
import { createApp } from "vue";
import App from "./App.vue";
const app = createApp(App);
app.mount("#app");
8. What are Filters in Vue.js?
Filters were a feature in Vue 2 used to format or transform data displayed in templates. They were applied using the pipe (|) syntax.
{{ message | capitalize }}Note: Filters have been removed in Vue 3. Instead, Vue 3 recommends using computed properties or methods to format data.
9. What is the purpose of nextTick() in Vue.js?
nextTick() is used to execute code after Vue has completed updating the DOM in response to reactive data changes. Since Vue updates the DOM asynchronously, nextTick() ensures that the DOM reflects the latest state before performing DOM-dependent operations.
10. How do you handle errors and exceptions in Vue.js applications?
Vue.js provides several ways to handle errors and exceptions:
- errorCaptured lifecycle hook: Catches errors from a component and its child components.
- Global error handler: In Vue 3, use app.config.errorHandler to handle application-wide errors.
- try...catch: Used to handle errors in asynchronous operations such as API calls.
11. How do you create custom events in Vue.js?
In Vue.js, custom events are created using the $emit() method in a child component. The parent component listens for the emitted event using the v-on directive or its shorthand @. This enables child-to-parent communication.
12. Explain Virtual Dom in Vue.js?
The Virtual DOM (VDOM) is a lightweight, in-memory representation of the real DOM. When the application state changes, Vue updates the Virtual DOM first, compares it with the previous Virtual DOM using a diffing algorithm, and then applies only the necessary changes to the real DOM.
This approach minimizes direct DOM manipulations, improving the application's performance and responsiveness, especially when data changes frequently.
13. Explain Hooks in Vue.js? what are the different built-in Hooks in Vue.js?
In Vue 3, lifecycle hooks are functions provided by the Composition API that allow you to run code at specific stages of a component's lifecycle, such as when it is created, mounted, updated, or unmounted.
Some commonly used built-in lifecycle hooks are:
- onBeforeMount(): Called before the component is mounted to the DOM.
- onMounted(): Called after the component has been mounted. Commonly used for API calls, DOM manipulation, and initializing third-party libraries.
- onBeforeUpdate(): Called before the component updates due to reactive data changes.
- onUpdated(): Called after the component has been updated.
- onBeforeUnmount(): Called before the component is removed from the DOM.
- onUnmounted(): Called after the component is removed. Used for cleanup tasks such as removing event listeners or clearing timers.
14. What is a Key in Vue.js?
A key is a special attribute used by Vue to uniquely identify elements or components, especially when rendering lists with v-for. It helps Vue efficiently track changes, reuse existing DOM elements, and update only the items that have changed instead of re-rendering the entire list.
15. Describe the distinction between 'v-show' and 'v-if' ?
v-show | v-if |
|---|---|
Toggles an element's visibility by changing its CSS display property. | Conditionally renders an element by adding or removing it from the DOM. |
The element always exists in the DOM. | The element is created and destroyed based on the condition. |
Higher initial render cost, but faster for frequent visibility toggles. | Lower initial render cost if the condition is false, but slower when toggling frequently. |
Best for elements that are shown or hidden frequently (e.g., dropdowns, tabs). | Best for elements that are rendered conditionally and infrequently (e.g., authentication, API-based content). |
16. What is the difference between '$emit' and '$on' in Vue.js?
$emit | $on |
|---|---|
Used to emit custom events from a child component. | Removed in Vue 3. It was used in Vue 2 to listen for emitted events on a Vue instance or event bus. |
Enables child-to-parent communication. | In Vue 3, the parent listens using v-on or @, not $on. |
Can pass data along with the emitted event. | No longer recommended or available in modern Vue.js. |
17. Who is the founder/ inventor of Vue.js?
Vue.js was created by Evan You. He developed the framework while working at Google, where he gained experience with AngularJS. Inspired by Angular's strengths, he created Vue.js as a lightweight, progressive, and flexible JavaScript framework. Vue.js was first released in 2014.
18. What is a local component in Vue.js?
A local component is a component that is registered inside a specific parent component and can be used only within that component's template. Unlike global components, local components are not available throughout the application, making them ideal for components used in a single place.
19. What is a global component in Vue.js?
A global component is a component that is registered once and can be used anywhere in the Vue application without importing or registering it in individual components. In Vue 3, global components are registered using the app.component() method.
20. What is the purpose of the 'data' function in Vue components?
The data() function is used to define a component's reactive state. It must return an object containing the data properties that Vue tracks for changes. In Vue components, data is a function so that each component instance has its own independent copy of the data.
<template>
<div>
<p>{{ message }}</p>
<button @click="updateMessage">Update Message</button>
</div>
</template>
<script>
export default {
data() {
return {
message: "Hello, GFG",
};
},
methods: {
updateMessage() {
this.message = "Welcome to GFG";
},
},
};
</script>
21. What is Vue CLI and how is it used?
Vue CLI (Command Line Interface) is a tool used to create, develop, and manage Vue.js projects. It provides a standard project structure, configures Webpack automatically, and simplifies development with features such as project scaffolding, hot reloading, linting, and testing.
Intermediate Level Questions
22. How do you pass data between components in Vue.js?
Vue.js provides several ways to pass data between components:
- Props: Pass data from a parent component to a child component.
- Custom Events ($emit): Send data from a child component to its parent.
- Provide/Inject: Share data from an ancestor component to any descendant component without prop drilling.
- Pinia (or Vuex): Manage and share global application state across multiple components.
<template>
<ChildComponent :message="parentMessage" />
</template>
<script>
import ChildComponent from "./ChildComponent.vue";
export default {
components: { ChildComponent },
data() {
return {
parentMessage: "Hello from Parent!",
};
},
};
</script>
<template>
<p>{{ message }}</p>
</template>
<script>
export default {
props: {
message: String,
},
};
</script>
23. What are slots in Vue.js?
Slots are placeholders in a child component that allow a parent component to pass and display custom content. They enable content projection, making components more reusable and flexible.
Vue supports:
- Default slots: For unnamed content.
- Named slots: For inserting content into specific placeholders.
- Scoped slots: Allow the child component to pass data back to the slot content in the parent.
24. How do you handle asynchronous operations in Vue.js?
Asynchronous operations in Vue.js are typically handled using Promises or async/await. API requests are commonly made using fetch or libraries like Axios. With async/await, try...catch is used to handle errors gracefully.
export default {
async mounted() {
try {
const response = await fetch("https://api.example.com/users");
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
},
};
25. What is the watcher in Vue.js?
A watcher is a Vue feature used to observe changes in reactive data or computed properties and execute a callback function when the value changes. Watchers are commonly used for side effects, such as making API calls, performing asynchronous operations, or responding to data changes.
export default {
data() {
return {
message: "Hello GFG",
};
},
watch: {
message(newValue, oldValue) {
console.log(`Message changed from ${oldValue} to ${newValue}`);
},
},
};
26. What is Vue-loader?
Vue Loader is a Webpack loader that processes Vue Single File Components (.vue files). It allows developers to write the template, script, and style of a component in a single file and compiles them into JavaScript modules that can be used in a Vue application.
Note: In modern Vue 3 projects, Vite is the recommended build tool, which uses @vitejs/plugin-vue instead of vue-loader.
27. What are the different types of directives present in Vue.js?
Directives are special attributes prefixed with v- that add reactive behavior to HTML elements.
Some commonly used Vue.js directives are:
- v-bind (:): Binds HTML attributes to data.
- v-model: Creates two-way data binding for form elements.
- v-for: Renders a list by iterating over an array or object.
- v-on (@): Attaches event listeners.
- v-if: Conditionally renders an element.
- v-else / v-else-if: Used with v-if for conditional rendering.
- v-show: Toggles an element's visibility using the CSS display property.
- v-slot: Defines named or scoped slots.
- v-html: Renders raw HTML.
- v-text: Updates an element's text content.
- v-once: Renders an element only once and skips future updates.
- v-pre: Skips Vue compilation for an element.
- v-cloak: Hides uncompiled templates until Vue is ready.
- v-memo (Vue 3): Memoizes part of the template to optimize rendering performance.
28. What is server-side rendering (SSR) in Vue.js?
Server-Side Rendering (SSR) is a rendering technique in which Vue components are rendered on the server, and the generated HTML is sent to the client. After the page loads, Vue hydrates the HTML to make it fully interactive.
- Faster initial page load.
- Improved SEO, as search engines receive fully rendered HTML.
- Better performance for users on slower networks or devices.
29. Explain the features of Vue.js.
Some key features of Vue.js are:
- Component-Based Architecture: Builds applications using reusable and independent components.
- Reactive Data Binding: Automatically updates the UI when data changes.
- Virtual DOM: Improves performance by updating only the changed parts of the DOM.
- Directives: Provides built-in directives such as v-if, v-for, v-model, and v-bind for dynamic rendering.
- Computed Properties and Watchers: Simplify data processing and respond to data changes.
- Single File Components (SFCs): Encapsulate template, logic, and styles in a single .vue file.
- Built-in Transitions and Animations: Easily add CSS transitions and animations.
- Vue Router: Supports client-side routing for Single-Page Applications (SPAs).
- State Management: Integrates with Pinia (recommended) or Vuex for managing shared application state.
- Server-Side Rendering (SSR): Improves SEO and initial page load performance.
30. How Do You Bind Class and Style in Vue.js?
Vue.js uses the v-bind directive (or its shorthand :) to dynamically bind CSS classes and inline styles.
- Class Binding (:class): Dynamically adds or removes CSS classes based on data.
- Style Binding (:style): Dynamically applies inline CSS styles.
Class Binding Example:
<div :class="{ active: isActive, 'text-danger': hasError }"></div>Style Binding Example:
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>31. How do you optimize the performance of a Vue.js application?
Some common ways to optimize a Vue.js application are:
- Use computed properties instead of methods for expensive calculations.
- Use key with v-for to help Vue efficiently update list items.
- Lazy load routes and components using Vue Router and dynamic imports.
- Use v-if and v-show appropriately based on rendering requirements.
- Avoid unnecessary watchers and reactive data.
- Use KeepAlive to cache dynamic components and avoid unnecessary re-creation.
- Leverage the Virtual DOM to minimize DOM updates.
- Use v-memo (Vue 3) to skip unnecessary re-renders when possible.
- Use Vue DevTools to identify and profile performance issues.
- Use Server-Side Rendering (SSR) or static site generation for faster initial page loads and better SEO.
32. What Is The Difference Between Functional And Class-based Components?
Functional Components | Class-Based Components |
|---|---|
Stateless and instance-less components. | Components written using ES classes with decorators. |
Do not have their own reactive state or lifecycle hooks. | Support state, lifecycle hooks, methods, and computed properties. |
Mainly used for simple presentational components. | Suitable for complex component logic (primarily in older Vue projects). |
Lightweight with less overhead. | Higher overhead due to component instances. |
Supported in Vue 3 as plain functions. | Not recommended in Vue 3; use the Composition API or Options API instead. |
33. Explain the Concept Of Higher-order Components in Vue.js?
A Higher-Order Component (HOC) is a function that takes a component as input and returns a new component with additional functionality or behavior. HOCs are inspired by higher-order functions in JavaScript.
However, HOCs are not commonly used in Vue.js. In Vue 3, the preferred approach for reusing logic is the Composition API (composables). Older Vue projects may also use mixins, while slots and custom directives are other common patterns for code reuse.
34. What Are the Best Practices for Component Naming in Vue.js?
Some recommended best practices for naming Vue.js components are:
- Use PascalCase: Name components using PascalCase (e.g., UserProfile.vue).
- Use Multi-word Names: Prefer multi-word component names (e.g., BaseButton.vue) to avoid conflicts with native HTML elements.
- Use Meaningful Names: Choose names that clearly describe the component's purpose (e.g., SubmitButton.vue, UserProfileCard.vue).
- Avoid Generic Names: Avoid vague names such as Button, Card, or Item.
- Keep File and Component Names Consistent: Use the same name for the component file and the component definition.
35. What are render functions in Vue.js?
A render function is a JavaScript function that creates and returns Virtual DOM nodes (VNodes) instead of using a template. Vue uses these VNodes to efficiently update the real DOM.
Render functions are useful for dynamic rendering and advanced UI logic that is difficult to express using templates. Internally, Vue compiles templates into render functions.
36. Can we call the REST API from Vue.js?
Yes. Vue.js can consume REST APIs using the native fetch() API or third-party libraries such as Axios. API requests are typically made inside lifecycle hooks such as mounted() (Options API) or onMounted() (Composition API).
37. Mention some of the array change detection methods in Vue.js.
Vue.js automatically detects changes made using the following array mutation methods and updates the UI reactively:
- push() : Adds elements to the end of the array.
- pop() : Removes the last element.
- shift() : Removes the first element.
- unshift() : Adds elements to the beginning of the array.
- splice() : Adds, removes, or replaces elements.
- sort() : Sorts the array.
- reverse() : Reverses the order of the array.
Advanced Level Questions
38. What is Vuex?
Vuex is a state management library for Vue.js that provides a centralized store to manage and share application state across components. It follows a predictable state management pattern, making it easier to manage complex application data.
39. In vue router, what are navigation guards?
Navigation guards are functions provided by Vue Router that control navigation between routes. They can allow, redirect, or cancel navigation before or after a route change. They are commonly used for authentication, authorization, and data fetching.
Vue Router provides three types of navigation guards:
- Global Guards: Apply to every route in the application (e.g., beforeEach, afterEach).
- Per-route Guards: Defined for a specific route using the beforeEnter option.
- In-component Guards: Defined inside a component (e.g., beforeRouteEnter, beforeRouteUpdate, beforeRouteLeave).
40. How do you handle errors and exceptions in Vue.js applications?
Vue.js provides multiple ways to handle errors and exceptions:
- errorCaptured lifecycle hook: Catches errors from a component and its child components.
- Global error handler: In Vue 3, use app.config.errorHandler to handle application-wide errors.
- try...catch: Used to handle errors in asynchronous operations such as API calls.
41. How can you install Vue.js in your project?
You can install Vue.js using the following methods:
- Using a CDN: Suitable for small projects or learning.
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>- Using npm: Install Vue as a project dependency.
npm install vue- Using Vite (Recommended for Vue 3): Create a new Vue project with Vite.
npm create vue@latest
cd my-vue-app
npm install
npm run dev
Note: Vue CLI (vue create) is still available for maintaining older projects but is in maintenance mode. For new Vue 3 applications, Vite is the recommended tool.
42. Why is it recommended not to use v-if and v-for directives together on the same element in Vue.js?
Using v-if and v-for on the same element is not recommended because it can lead to unexpected behavior, reduced performance, and less readable code.
Reasons:
- Directive Priority: In Vue 3, v-if has higher priority than v-for, which can cause the loop variable to be unavailable when the v-if condition is evaluated.
- Performance: v-if is evaluated during every iteration of the v-for loop, resulting in unnecessary computations.
- Readability: Mixing both directives makes templates harder to understand and maintain.
Recommended Approaches:
- Use a computed property to filter the list before rendering.
- Move v-if to a wrapper element instead of placing it on the same element as v-for.
43. Give an example to demonstrate how can you use event handlers in Vue.js?
In Vue.js, event handlers respond to user interactions such as clicks, key presses, form submissions, and mouse events. Events are attached using the v-on directive or its shorthand @, and the corresponding methods are defined in the component.
<template>
<div>
<button @click="handleClick">Click me!</button>
<p v-if="clicked">Button was clicked!</p>
</div>
</template>
<script>
export default {
data() {
return {
clicked: false,
};
},
methods: {
handleClick() {
this.clicked = true;
},
},
};
</script>
44. Name some websites/companies that use Vue.js.
Some well-known companies and websites that use Vue.js include:
- Netflix
- GitLab
- Adobe
- Alibaba
- Xiaomi
- Behance (Adobe)
- BMW
- Nintendo
45. Can You Explain the Single File Components in Vue.js?
A Single File Component (SFC) is a Vue component that encapsulates its template, logic, and styles in a single .vue file. This improves modularity, reusability, and maintainability by keeping all related code together.
A typical SFC consists of:
- <template> : Defines the HTML structure.
- <script> : Contains the component's logic.
- <style> : Defines component-specific styles.
46. What is $parent property in Vue.js?
The $parent property provides a child component with direct access to its immediate parent component. It allows the child to access the parent's data, methods, and properties.
this.$parent.parentMethod();47. What is vue plugin?
A Vue plugin is a reusable piece of code that adds application-wide functionality to a Vue application. Plugins can register global components, directives, methods, provide services, or integrate third-party libraries.
Plugins are installed using the app.use() method in Vue 3.
48. Discuss the v-cloak directive in Vue.js.
The v-cloak directive is used to hide uncompiled Vue templates until the Vue application is fully mounted. It prevents the Flash of Uncompiled Content (FOUC) by keeping elements hidden until Vue finishes compiling the template. Once compilation is complete, Vue automatically removes the v-cloak attribute.
49. List out some of the event modifiers in Vue.js?
Event modifiers are used with the v-on directive (or @) to modify how events are handled.
Some commonly used event modifiers are:
- .stop : Stops event propagation.
- .prevent : Prevents the default browser behavior.
- .capture : Registers the event listener in the capture phase.
- .once : Executes the event handler only once.
- .self : Triggers the event only when the event originates from the element itself.
- .passive : Improves scrolling performance by indicating that the event handler will not call preventDefault().
50. What are some popular testing frameworks for Vue.js?
Some popular testing frameworks and tools for Vue.js are:
- Vitest: The recommended unit testing framework for Vue 3 and Vite projects.
- Vue Test Utils: The official utility library for testing Vue components.
- Jest: A popular JavaScript testing framework, commonly used in existing Vue projects.
- Cypress: Used for end-to-end (E2E) testing of Vue applications.
- Mocha: A flexible JavaScript testing framework that can be used with Vue.js.