List of 300 VueJS Interview Questions
Click ⭐if you like the project. Pull Request are highly appreciated.
-
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.
-
Below are the some of major features available with VueJS
- Virtual DOM: It uses virtual DOM similar to other existing frameworks such as ReactJS, Ember etc. Virtual DOM is a light-weight in-memory tree representation of the original HTML DOM and updated without affecting the original DOM.
- Components: Used to create reusable custom elements in VueJS applications.
- Templates: VueJS provides HTML based templates that bind the DOM with the Vue instance data
- Routing: Navigation between pages is achieved through vue-router
- Light weight: VueJS is light weight library compared to other frameworks
-
VueJS provides 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** 1. v-if: The v-if directive adds or removes DOM elements based on the given expression. For example, the below button will not show if isLoggedIn is set to false.
<button v-if="isLoggedIn">Logout</button>
You can also control multiple elements with a single v-if statement by wrapping all the elements in a element with the condition. For example, you can have both label and button together conditionally applied,
<template v-if="isLoggedIn"> <label> Logout </button> <button> Logout </button> </template>
2. v-else: This directive is used to display content only when the expression adjacent v-if resolves to false. This is similar to else block in any programming language to display alternative content and it is preceded by v-if or v-else-if block. You don't need to pass any value to this. For example, v-else is used to display LogIn button if isLoggedIn(not logged in) is set to false.
<button v-if="isLoggedIn"> Logout </button> <button v-else> Log In </button>
3. v-else-f: This directive is used when we need more than two options to be checked. For example, ifLoginDisabled property is disabled then we need to prevent user to login instead just display the label. This can be achieved through v-else statement.
<button v-if="isLoggedIn"> Logout </button> <label v-else-if="isLoginDisabled"> User login disabled </label> <button v-else> Log In </button>
4. v-show: This directive is similar to v-if but it renders all elements to the DOM and then uses the CSS display property to show/hide elements. This directive is recommended if the elements are switched on and off frequently.
<span if-show="user.name">Welcome user,{{user.name}}</span>
-
Below are some of the main differences between 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 tab but v-show doesn't support.
-
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.
- 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' } ] } })
You can also use
of
as the delimiter instead ofin
, similar to javascript iterators. 2. Object usage:<div id="object" v-for="(value, key, index) in object"> {{ index }}. {{ key }}: {{ value }} </div> var vm = new Vue({ el: '#object', data: { user: { firstName: 'John', lastName: 'Locke', age: 30 } } })
-
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.
-
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>
-
Vue always try to render elements as efficient as possible. So it tries to reuse the elements instead of building them from scratch. But this behavior may cause problems in few scenarios. For example, if you try to render the same input element in both
v-if
andv-else
blocks then it holds the previous value as below,<template v-if="loginType === 'Admin'"> <label>Admin</label> <input placeholder="Enter your ID"> </template> <template v-else> <label>Guest</label> <input placeholder="Enter your name"> </template>
In this case, it shouldn't reuse. We can make both input elements as separate by applying key attribute as below,
<template v-if="loginType === 'Admin'"> <label>Admin</label> <input placeholder="Enter your ID" key="admin-id"> </template> <template v-else> <label>Guest</label> <input placeholder="Enter your name" key="user-name"> </template>
The above code make sure both inputs are independent and doesn't impact each other.
-
It is recommended not to use v-if on the same element as v-for. Because v-for directive has a higher priority than v-if. There are two cases where developers try to use this combination,
- To filter items in a list For example, if you try to filter the list using v-if tag,
<ul> <li v-for="user in users" v-if="user.isActive" :key="user.id" > {{ user.name }} <li> </ul>
This can be avoided by preparing the filtered list using computed property on the initial list
computed: { activeUsers: function () { return this.users.filter(function (user) { return user.isActive }) } } ...... // ...... // <ul> <li v-for="user in activeUsers" :key="user.id"> {{ user.name }} <li> </ul>
- To avoid rendering a list if it should be hidden For example, if you try to conditionally check if the user is to show or hide
<ul> <li v-for="user in users" v-if="shouldShowUsers" :key="user.id" > {{ user.name }} <li> </ul>
This can be solved by moving the condition to a parent by avoiding this check for each user
<ul v-if="shouldShowUsers"> <li v-for="user in users" :key="user.id" > {{ user.name }} <li> </ul>
-
In order to track each node’s identity, and thus reuse and reorder existing elements, you need to provide a unique
key
attribute for each item with inv-for
iteration. An ideal value for key would be the unique id of each item. Let us take an example usage,<div v-for="item in items" :key="item.id"> {{item.name}} </div>
Hence, It is always recommended to provide a key with v-for whenever possible, unless the iterated DOM content is simple. Note: You shouldn’t use non-primitive values like objects and arrays as v-for keys. Use string or numeric values instead.
-
As the name suggests, mutation methods modifies the original array. Below are the list of array mutation methods which trigger view updates.
- push()
- pop()
- shift()
- unshift()
- splice()
- sort()
- 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' })
-
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,
- filter()
- concat()
- 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.
-
Vue cannot detect changes for the array in the below two cases,
- When you directly set an item with the index,For example,
vm.tods[indexOfTodo] = newTodo
- When you modify the length of the array, For example,
vm.todos.length = todosLength
You can overcome both the caveats using
set
andsplice
methods, Let's see the solutions with an examples, First use case solution// Vue.set Vue.set(vm.todos, indexOfTodo, newTodoValue) (or) // Array.prototype.splice vm.todos.splice(indexOfTodo, 1, newTodoValue)
Second use case solution
vm.todos.splice(todosLength)
- When you directly set an item with the index,For example,
-
Vue cannot detect changes for the object in property addition or deletion., Lets take an example of user data changes,
var vm = new Vue({ data: { user: { name: 'John' } } }) // `vm.name` is now reactive vm.email = john@email.com // `vm.email` is NOT reactive
You can overcome this scenario using the Vue.set(object, key, value) method or Object.assign(),
Vue.set(vm.user, 'email', john@email.com); (or) vm.user = Object.assign({}, vm.user, { email: john@email.com })
-
You can also use integer type(say 'n') for v-for directive which repeat the element many times.
<div> <span v-for="n in 20">{{ n }} </span> </div>
It displays the number 1 to 20.
-
Just similar to v-if directive on template, you can also use a 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>