Vue.js Interview Questions
Vue.js Interview Questions

Vue.js is an open-source, progressive Javascript framework for building user interfaces that aim to be incrementally adoptable. The core library of VueJS is focused on the view layer only, and is easy to pick up and integrate with other libraries or existing projects.

Contents

What are the major features of VueJS?

  1. Virtual DOM: It uses virtual DOM similar to other existing frameworks such as ReactJS, Ember etc. Virtual DOM is a lightweight in-memory tree representation of the original HTML DOM and is updated without affecting the original DOM.
  2. Components: Used to create reusable custom elements in VueJS applications.
  3. Templates: VueJS provides HTML-based templates that bind the DOM with the Vue instance data
  4. Routing: Navigation between pages is achieved through vue-router
  5. Lightweight: VueJS is a lightweight library compared to other frameworks.

What are the lifecycle methods of VueJS?

Lifecycle hooks are a window into how the library you’re using works behind the scenes. Using these hooks, you will know when your component is created, added to the DOM, updated, or destroyed. Let’s look at the lifecycle diagram before going to each lifecycle hook in detail,

What are the lifecycle methods of VueJS?
What are the lifecycle methods of VueJS?

What are the conditional directives?

VueJS provides a set of directives to show or hide elements based on conditions. The available directives are: v-if, v-else, v-else-if and v-show

What is vue instance?

Every Vue application works by creating a new Vue instance with the Vue function. Generally the variable vm (short for ViewModel) is used to refer Vue instance. You can create vue instance as below,

var vm = new Vue({
  // options
})

As mentioned in the above code snippets, you need to pass options object. You can find the full list of options in the API reference.

How to create an instance of Vue js.

You can create a Vue instance with the Vue function:

var vm = new Vue({
  // options
})

Explain the differences between one-way data flow and two-way data binding?

In one-way data flow the view(UI) part of application does not updates automatically when data Model is change we need to write some custom code to make it updated every time a data model is changed.

In Vue js v-bind is used for one-way data flow or binding.

In two-way data binding the view(UI) part of application automatically updates when data Model is changed.

In Vue.js v-model directive is used for two way data binding.

What is the difference between v-show and v-if directives?

Below are some of the main differences between v-show and v-if directives,

  1. v-if only renders the element to the DOM if the expression passes whereas v-show renders all elements to the DOM and then uses the CSS display property to show/hide elements based on expression.
  2. v-if supports v-else and v-else-if directives whereas v-show doesn’t support else directives.
  3. v-if has higher toggle costs while v-show has higher initial render costs. i.e, v-show has a performance advantage if the elements are switched on and off frequently, while the v-if has the advantage when it comes to initial render time.
  4. v-if supports <template> tab but v-show doesn’t support.

What is the purpose of v-for directive?

The built-in v-for directive allows us to loop through items in an array or object. You can iterate on each element in the array or object.

  1. Array usage:
<ul id="list">
  <li v-for="(item, index) in items">
    {{ index }} - {{ item.message }}
  </li>
</ul>

var vm = new Vue({
  el: '#list',
  data: {
    items: [
      { message: 'John' },
      { message: 'Locke' }
    ]
  }
})

How do you achieve conditional group of elements?

You can achieve conditional group of elements(toggle multiple elements at a time) by applying v-if directive on <template> element which works as invisible wrapper(no rendering) for group of elements.

For example, you can conditionally group user details based on valid user condition.

<template v-if="condition">
  <h1>Name</h1>
  <p>Address</p>
  <p>Contact Details</p>
</template>

What are the array detection mutation methods?

As the name suggests, mutation methods modifies the original array.

Below are the list of array mutation methods which trigger view updates.

  1. push()
  2. pop()
  3. shift()
  4. unshift()
  5. splice()
  6. sort()
  7. reverse()

If you perform any of the above mutation method on the list then it triggers view update. For example, push method on array named ‘items’ trigger a view update,

vm.todos.push({ message: 'Baz' })

What are the array detection non-mutation methods?

The methods which do not mutate the original array but always return a new array are called non-mutation methods.

Below are the list of non-mutation methods,

  1. filter()
  2. concat()
  3. slice()

For example, lets take a todo list where it replaces the old array with new one based on status filter,

vm.todos = vm.todos.filter(function (todo) {
  return todo.status.match(/Completed/)
})

This approach won’t re-render the entire list due to VueJS implementation.

How do you use v-for directive with a range?

You can also use integer type(say ‘n’) for v-for directive which repeats the element many times.

<div>
  <span v-for="n in 20">{{ n }} </span>
</div>

It displays the number 1 to 20.

How do you use v-for directive on template?

Just similar to v-if directive on template, you can also use a <template> tag with v-for directive to render a block of multiple elements.

Let’s take a todo example,

<ul>
  <template v-for="todo in todos">
    <li>{{ todo.title }}</li>
    <li class="divider"></li>
  </template>
</ul>

How do you use event handlers?

You can use event handlers in vue similar to plain javascript. The method calls also support the special $event variable.

<button v-on:click="show('Welcome to VueJS world', $event)">
  Submit
</button>

methods: {
  show: function (message, event) {
    // now we have access to the native event
    if (event) event.preventDefault()
    console.log(message);
  }
}

What are the event modifiers provided by vue?

Normally, javascript provides event.preventDefault() or event.stopPropagation() inside event handlers. You can use methods provided by vue, but these methods are meant for data logic instead of dealing with DOM events. Vue provides below event modifiers for v-on and these modifiers are directive postfixes denoted by a dot.

  1. .stop
  2. .prevent
  3. .capture
  4. .self
  5. .once
  6. .passive

Let’s take an example of stop modifier,

<!-- the click event's propagation will be stopped -->
<a v-on:click.stop="methodCall"></a>

You can also chain modifiers as below,

<!-- modifiers can be chained -->
<a v-on:click.stop.prevent="doThat"></a>

How do you define custom key modifier aliases?

You can define custom key modifier aliases via the global config.keyCodes. There are few guidelines for the properties

  1. You can’t use camelCase. Instead you can use kebab-case with double quotation marks
  2. You can define multiple values in an array format
Vue.config.keyCodes = {
  f1: 112,
  "media-play-pause": 179,
  down: [40, 87]
}

What are the supported System Modifier Keys?

Vue supports below modifiers to trigger mouse or keyboard event listeners when the corresponding key is pressed,

  1. .ctrl
  2. .alt
  3. .shift
  4. .meta

Lets take an example of control modifier with click event,

<!-- Ctrl + Click -->
<div @click.ctrl="doSomething">Do something</div>

How do you implement two-way binding?

You can use the v-model directive to create two-way data bindings on form input, textarea, and select elements.

Lets take an example of it using input component,

<input v-model="message" placeholder="Enter input here">
<p>The message is: {{ message }}</p>

Remember, v-model will ignore the initial valuechecked or selected attributes found on any form elements. So it always use the Vue instance data as the source of truth.

What are the supported modifiers on model?

There are three modifiers supported for v-model directive.

1. lazy: By default, v-model syncs the input with the data after each input event. You can add the lazy modifier to instead sync after change events.

<!-- synced after "change" instead of "input" -->
<input v-model.lazy="msg" >

2. number: If you want user input to be automatically typecast as a number, you can add the number modifier to your v-model. Even with type=”number”, the value of HTML input elements always returns a string. So, this typecast modifier is required.

<input v-model.number="age" type="number">

3. trim: If you want whitespace from user input to be trimmed automatically, you can add the trim modifier to your v-model.

<input v-model.trim="msg">

What are components and give an example?

Components are reusable Vue instances with a name. They accept the same options as new Vue, such as data, computed, watch, methods, and lifecycle hooks(except few root-specific options like el).

Lets take an example of counter component,

// Define a new component called button-counter
Vue.component('button-counter', {
  template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
  data: function () {
    return {
      count: 0
    }
  },
})

Let’s use this component inside a root Vue instance created with new Vue

<div id="app">
  <button-counter></button-counter>
</div>

var vm = new Vue({ el: '#app' });

What are props?

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. You can pass those list of values as props option and use them as similar to data variables in template.

Vue.component('todo-item', {
  props: ['title'],
  template: '<h2>{{ title }}</h2>'
})

Once the props are registered, you can pass them as custom attributes.

<todo-item title="Learn Vue conceptsnfirst"></todo-item>

How do you communicate from child to parent using events?

If you want child wants to communicate back up to the parent, then emit an event from child using $emit object to parent,

Vue.component('todo-item', {
  props: ['todo'],
  template: `
    <div class="todo-item">
      <h3>{{ todo.title }}</h3>
      <button v-on:click="$emit('increment-count', 1)">
        Add
      </button>
      <div v-html="todo.description"></div>
    </div>
  `
})

Now you can use this todo-item in parent component to access the count value.

<ul v-for="todo in todos">
  <li>
    <todo-item
      v-bind:key="todo.id"
      v-bind:todo="todo"
      v-on:increment-count="total += 1"
    /></todo-item>
  </li>
</ul>
<span> Total todos count is {{total}}</span>

What are slots?

Vue implements a content distribution API using the element to serve as distribution outlets for content created after the current Web Components spec draft.

Let’s create an alert component with slots for content insertion,

Vue.component('alert', {
  template: `
    <div class="alert-box">
      <strong>Error!</strong>
      <slot></slot>
    </div>
  `
})

Now you can insert dynamic content as below,

<alert>
  There is an issue with in application.
</alert>

What is global registration in components?

The components which are globally registered can be used in the template of any root Vue instance (new Vue) created after registration.

In the global registration, the components created using Vue.component as below,

Vue.component('my-component-name', {
  // ... options ...
})

Let’s take multiple components which are globally registered in the vue instance,

Vue.component('component-a', { /* ... */ })
Vue.component('component-b', { /* ... */ })
Vue.component('component-c', { /* ... */ })

new Vue({ el: '#app' })

The above components can be used in the vue instance,

<div id="app">
  <component-a></component-a>
  <component-b></component-b>
  <component-c></component-c>
</div>

Remember that the components can be used in subcomponents as well.

What is the difference between local and global registration in module system?

In local registration, you need to create each component in components folder(optional but it is recommended) and import them in another component file components section.

Let’s say you want to register component A and B in component C, the configuration seems as below,

import ComponentA from './ComponentA'
import ComponentB from './ComponentB'

export default {
  components: {
    ComponentA,
    ComponentB
  },
  // ...
}

Now both ComponentA and ComponentB can be used inside ComponentC‘s template.

In global registration, you need to export all common or base components in a separate file. But some of the popular bundlers like webpack make this process simpler by using require.context to globally register base components in the below entry file(one-time).

import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

const requireComponent = require.context(
  // The relative path of the components folder
  './components',
  // Whether or not to look in subfolders
  false,
  // The regular expression used to match base component filenames
  /Base[A-Z]\w+\.(vue|js)$/
)

requireComponent.keys().forEach(fileName => {
  // Get component config
  const componentConfig = requireComponent(fileName)

  // Get PascalCase name of component
  const componentName = upperFirst(
    camelCase(
      // Strip the leading `./` and extension from the filename
      fileName.replace(/^\.\/(.*)\.\w+$/, '$1')
    )
  )

  // Register component globally
  Vue.component(
    componentName,
    // Look for the component options on `.default`, which will
    // exist if the component was exported with `export default`,
    // otherwise fall back to module's root.
    componentConfig.default || componentConfig
  )
})

What are possible prop types?

You can declare props with type or without type. But it is recommended to have prop types because it provides the documentation for the component and warns the developer for any incorrect data type being assigned.

props: {
  name: String,
  age: Number,
  isAuthenticated: Boolean,
  phoneNumbers: Array,
  address: Object
}

As mentioned in the above code snippet, you can list props as an object, where the properties’ names and values contain the prop names and types, respectively.

What is vue router and their features?

Vue Router is a official routing library for single-page applications designed for use with the Vue.js framework.

Below are their features,

  1. Nested route/view mapping
  2. Modular, component-based router configuration
  3. Route params, query, wildcards
  4. View transition effects powered by Vue.js’ transition system
  5. Fine-grained navigation control
  6. Links with automatic active CSS classes
  7. HTML5 history mode or hash mode, with auto-fallback in IE9
  8. Restore scroll position when going back in history mode

What is dynamic route matching?

Sometimes it may be required to map routes to the same component based on a pattern.

Let’s take a user component with the mapped URLs like /user/john/post/123 and /user/jack/post/235 using dynamic segments,

const User = {
  template: '<div>User {{ $route.params.name }}, PostId: {{ route.params.postid }}</div>'
}

const router = new VueRouter({
  routes: [
    // dynamic segments start with a colon
    { path: '/user/:name/post/:postid', component: User }
  ]
})

What is Vuex?

VueX is a state management pattern and library for the application using Vue JS. it acts as a centralized store for all the different components in your Vue JS application. It has rules to ensure that the state can be only mutated in a predictable fashion. It can be integrated with the official devtool extension of Vue to provide additional features. Vuex mainly helps in dealing with shared state management with the cost of more concepts and boilerplate.

What is vuex plugin?

The vuex plugin is an option hat exposes hooks for each mutation. It is a normal function that receives the store as the only argument. You can create your own plugin or use built-in plugins.

What is vuex store?

A Vuex “store” is basically a container that holds your application state.

Do I need promise for vuex?

Yes, vuex requires Promise. If your supporting browsers do not implement Promise (e.g. IE), you can use a polyfill library, such as es6-promise using npm or yarn.

How to import js file in the Vue component?

There are two ways to import a JavaScript library to the Vue Component.

The first is to import a local JavaScript library. Here, you can import the JavaScript library by using the ‘import’ keyword inside the script tag of your Vue file.

import * as mykey from '../assets/js/mykey.js';

The second way is to include your external JavaScript file into the mounted hook of your Vue component.

How to call rest API from Vue js?

We can use various HTTP libraries to call REST Api’s from Vue JS. One of the popular libraries is Axios. It simple to use and lightweight. To include it in your project, execute the following command.

npm install axios --save

Implementing GET method using Axios in Vue JS

axios({ method: "GET", "URL": "https://httpbin.org/ip" }).then(result => {
                this.ip = result.data.origin;
            }, error => {
                console.error(error);
            });


We can send an HTTP request using Axios with a promise. If the request is successful, we’ll get the result.

What are filters?

Filters can be used to apply common text formatting. These Filters should be appended to the end of the JavaScript expression, denoted by the “pipe” symbol. You can use them in two specific cases:

  1. mustache interpolations
  2. v-bind expressions

What are the different ways to create filters?

You can define filters in two ways,

  1. Local filters: You can define local filters in a component’s options. In this case, filter is applicable to that specific component.
  2. Global filters: You can also define a filter globally before creating the Vue instance. In this case, filter is applicable to all the components with in the vue instance,

Is it possible to pass parameters for filters?

Yes, you can pass arguments for a filter similar to a javascript function. The generic structure of filter parameters would be as follows,

What are plugins and their various services?

Vue CLI uses a plugin-based architecture where each plugin can modify the internal webpack configuration and inject commands to vue-cli-service. i.e, Each feature is implemented as a plugin. This architecture makes Vue CLI flexible and extensible.

Plugins provides global-level functionality to Vue application. The plugins provide various services,

  1. Add some global methods or properties. For example, vue-custom-element
  2. Add one or more global assets (directives, filters and transitions). For example, vue-touch
  3. Add some component options by global mixin. For example, vue-router
  4. Add some Vue instance methods by attaching them to Vue.prototype.
  5. A library that provides an API of its own, while at the same time injecting some combination of the above. For example, vue-router

What are mixins?

Mixin gives us a way to distribute reusable functionalities in Vue components. These reusable functions are merged with existing functions. A mixin object can contain any component options. Let us take an example of mixin with created lifecycle which can be shared across components,

What are global mixins?

Sometimes there is a need to extend the functionality of Vue or apply an option to all Vue components available in our application. In this case, mixins can be applied globally to affect all components in Vue. These mixins are called as global mixins.

What is the benefit of render functions over templates?

In VueJS, the templates are very powerful and recommended to build HTML as part of your application. However, some of the special cases like dynamic component creation based on input or slot value can be achieved through render functions. Also, these functions gives the full programmatic power of javascript eco system.

What is a render function?

Render function is a normal function which receives a createElement method as it’s first argument used to create virtual nodes. Internally Vue.js’ templates actually compile down to render functions at build time. Hence templates are just syntactic sugar of render functions.

What are functional components?

The functional components are just simple functions to create simple components just by passing a context. Every functional component follows two rules,

  1. Stateless: It doesn’t keep any state by itself
  2. Instanceless: It has no instance, thus no this

What are the similarities between VueJS and ReactJS?

Even though ReactJS and VueJS are two different frameworks there are few similarities(apart from the common goal of utilized in interface design) between them.

  1. Both frameworks are based on the Virtual DOM model
  2. They provide features such Component-based structure and reactivity
  3. They are intended for working with the root library, while all the additional tasks are transferred to other libraries(routing, state management etc).

What is the difference between VueJS and ReactJS?

Even though VueJS and ReactJS share few common features there are many difference between them.

Let’s list down them in a table format.

FeatureVueJSReactJS
TypeJavaScript MVC FrameworkJavaScript Library
PlatformPrimarily focused on web developmentBoth Web and Native
Learning CurveEasy to learn the frameworkA steep learning curve and requires deep knowledge
SimplicityVue is simpler than ReactReact is more complex than Vue
Bootstrap ApplicationVue-cliCRA (Create React App)

What are the advantages of VueJS over ReactJS?

Vue has the following advantages over React

  1. Vue is smaller and faster
  2. The convenient templates ease the process of developing
  3. It has simpler javascript syntax without learning JSX

What are the advantages of ReactJS over VueJS?

React has the following advantages over Vue

  1. ReactJS gives more flexibility in large apps developing
  2. Easy to test
  3. Well-suited for mobile apps creation
  4. The eco system is quite big and well matured.

What are the differences between VueJS and Angular?

The the syntax of Vue and Angular is common at some points because Angular is the basis for VueJS development in the beginning.

But there are many differences between VueJS and Angular as listed,

FeatureVueJSAngular
ComplexityEasy to learn, simple API and designThe framework is bit huge and need some learning curve on typescript etc
Binding of DataOne-way bindingTwo-way binding
Learning CurveEasy to learn the frameworkA steep learning curve and requires deep knowledge
FoundersCreated by Former Google EmployeePowered by Google
Initial ReleaseFebruary 2014September 2016
ModelBased on Virtual DOM(Document Object Model)Based on MVC(Model-View-Controller)
Written inJavaScriptTypeScript

What is the purpose of keep alive tag?

Keep-alive tag is an abstract component used to preserve component state or avoid re-rendering. When you wrapped tag around a dynamic component, it caches the inactive component instances without destroying them.

What are async components?

In large applications, we may need to divide the app into smaller chunks and only load a component from the server when it’s needed. To make this happen, Vue allows you to define your component as a factory function that asynchronously resolves your component definition. These components are known as async component.

What are inline templates?

If you keep an inline-template on a child component then it will use its inner content as a template instead of treating as reusable independent content.

What are X Templates?

Apart from regular templates and inline templates, you can also define templates using a script element with the type text/x-template and then referencing the template by an id.

What is a vuejs loader?

Vue loader is a loader for webpack that allows you to author Vue components in a format called Single-File Components (SFCs).

Beginner Vue Interview Questions to Practice

Before we wrap this article up, here are a few other easy Vue interview questions you might be asked at your upcoming meeting:

  • What is a Vue instance and how do you create it?
  • How do you access the root instance?
  • How do you access a component’s parent instance?
  • What are the differences between static and dynamic props?
  • What are the different ways you can create a component in Vue?
  • What are the pros and cons of single-file components?
  • What is the Vue CLI?
  • What are the features provided by Vue CLI?
  • How do you use v-for directive with a range?
  • What are hook functions provided by directives?

Intermediate Vue.js Interview Questions to Practice

Before we wrap this section up, here are a few other intermediate Vue interview questions you might be asked at your upcoming interview.

  • What are the event modifiers provided by Vue?
  • How do you chain multiple filters?
  • How do you conditionally render a group of elements?
  • How do you register a component inside another component?
  • How do you watch for nested data changes?
  • How are styles scoped inside a Vue component?
  • Is it possible to combine local and global styles?
  • Are parent styles leaked into child components?
  • What are mixins in Vue?
  • What are the merging strategies in mixins?

Advanced VueJS Interview Questions to Practice

Before we wrap this section up, here are a few other advanced Vue interview questions you might be asked at your upcoming technical assessment:

  • What are dynamic components in Vue?
  • What are async components in Vue?
  • What is the global registration of components in Vue?
  • What is dynamic route matching?
  • How do you resolve circular dependencies between components?
  • How can you create duplicate virtual nodes in a component?
  • What are some common sources of memory leaks in Vue apps?
  • What are some best practices to follow to create an accessible Vue application?
  • What is namespacing in vuex?
  • What are modules in vuex?
  • What are functional components?
  • What are Composition API in Vue?
  • What are the different ways to add animations in a Vue application?
  • What are plugins in Vue?
  • What are some common techniques to optimize your Vue application?

Vue.js Interview Questions

What is Vue.js?/ What do you understand by Vue.js?

Vue.js is a progressive framework of JavaScript used to create Dynamic User Interfaces and single-page applications.

Why is Vue.js called a progressive framework?

Vue.js is called a progressive framework because it is being changed and developed continually.

Why is Vue.js supposed to be a competitor of Angular in the upcoming days?

Vue.js is also used to build User Interfaces and single-page applications like Angular. Nowadays, it is evolving very fast, and with time, new libraries and extensions are coming into existence.