FrontendDeveloper.in

Vue.js Interview Questions

  • Question 1

    What is VueJS?

    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.

  • Question 2

    What are the major features of VueJS?

    Below are the some of major features available with VueJS

    1. 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.
    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. Light weight: VueJS is light weight library compared to other frameworks.
  • Question 3

    What are the lifecycle methods of VueJS?

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

    1. Creation(Initialization): Creation Hooks allow you to perform actions before your component has even been added to the DOM. You need to use these hooks if you need to set things up in your component both during client rendering and server rendering. Unlike other hooks, creation hooks are also run during server-side rendering.
    2. beforeCreate: This hook runs at the very initialization of your component. hook observes data and initialization events in your component. Here, data is still not reactive and events that occur during the component's lifecycle have not been set up yet.
    new Vue({
    data: {
    count: 10
    },
    beforeCreate: function () {
    console.log('Nothing gets called at this moment')
    // `this` points to the view model instance
    console.log('count is ' + this.count);
    }
    })
    // count is undefined
    
    1. created: This hook is invoked when Vue has set up events and data observation. Here, events are active and access to reactive data is enabled though templates have not yet been mounted or rendered.
    new Vue({
    data: {
    count: 10
    },
    created: function () {
    // `this` points to the view model instance
    console.log('count is: ' + this.count)
    }
    })
    // count is: 10
    

    Note: Remember that, You will not have access to the DOM or the target mounting element (this.$el) inside of creation hooks 2. Mounting(DOM Insertion): Mounting hooks are often the most-used hooks and they allow you to access your component immediately before and after the first render.

    1. beforeMount: The beforeMount allows you to access your component immediately before and after the first render.
    new Vue({
    beforeMount: function () {
    // `this` points to the view model instance
    console.log(`this.$el is yet to be created`);
    }
    })
    
    1. mounted: This is a most used hook and you will have full access to the reactive component, templates, and rendered DOM (via. this.$el). The most frequently used patterns are fetching data for your component.
    new Vue({
    el: '#app',
    mounted: function() {
    console.log(this.$el.textContent); // I'm text inside the component.
    }
    })
    
    1. Updating (Diff & Re-render): Updating hooks are called whenever a reactive property used by your component changes, or something else causes it to re-render
    2. beforeUpdate: The beforeUpdate hook runs after data changes on your component and the update cycle begins, right before the DOM is patched and re-rendered.
    ...// rest of the code
    new Vue({
    el: '#app',
    data() {
    return {
    counter: 0
    }
    },
    created: function() {
    setInterval(() => {
    this.counter++
    }, 1000)
    },
    
    beforeUpdate: function() {
    console.log(this.counter) // Logs the counter value every second, before the DOM updates.
    }
    })
    
    1. updated: This hook runs after data changes on your component and the DOM re-renders.
    ...//
    new Vue({
    el: '#app',
    data() {
    return {
    counter: 0
    }
    },
    created: function() {
    setInterval(() => {
    this.counter++
    }, 1000)
    },
    updated: function() {
    console.log(+this.$refs['dom'].textContent === this.counter) // Logs true every second
    }
    })
    
    1. Destruction (Teardown): Destruction hooks allow you to perform actions when your component is destroyed, such as cleanup or analytics sending.
    2. beforeDestroy: beforeDestroy is fired right before teardown. If you need to cleanup events or reactive subscriptions, beforeDestroy would probably be the time to do it. Your component will still be fully present and functional.
    new Vue ({
    data() {
    return {
    message: 'Welcome VueJS developers'
    }
    },
    
    beforeDestroy: function() {
    this.message = null
    delete this.message
    }
    })
    
    1. destroyed: This hooks is called after your component has been destroyed, its directives have been unbound and its event listeners have been removed.
    new Vue ({
    destroyed: function() {
    console.log(this) // Nothing to show here
    }
    })
    
  • Question 4

    What are the different API styles available?

    The Vue components can be created in two different API styles

    1. Options API: The Options API uses component logic using an object of options such as data, props, computed, methods and life cycle methods etc. The properties will be accessible inside functions using component instance(i.e, this).

    2. Composition API: The Composition API uses component logic using imported API functions. The Single File Components(SFCs) requires setup attribute(<script setup>) to use imported variables and functions directly inside template section.

  • Question 5

    What are the conditional directives?

    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 <template> 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 is set to false(not logged in).

    <button v-if="isLoggedIn"> Logout </button>
    <button v-else> Log In </button>
    

    3. v-else-if: This directive is used when we need more than two options to be checked. For example, we want to display some text instead of LogIn button when ifLoginDisabled property is set to true. 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 v-show="user.name">Welcome user,{{user.name}}</span>
    
  • Question 6

    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.
  • Question 7

    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' }
    ]
    }
    })
    

    You can also use of as the delimiter instead of in, similar to javascript iterators.

    1. Object usage:
    {{ index }}. {{ key }}: {{ value }}
    
    var vm = new Vue({
    el: '#object',
    data: {
    user: {
    firstName: 'John',
    lastName: 'Locke',
    age: 30
    }
    }
    })
    
  • Question 8

    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.

  • Question 9

    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>
    </template>
    
  • Question 10

    How do you reuse elements with key attribute?

    Vue always tries 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 and v-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.

  • Question 11

    Why should not use if and for directives together on the same element?

    It is recommended not to use v-if on the same element as v-for. Because v-if directive has a higher priority than v-for.

    There are two cases where developers try to use this combination,

    1. 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>
    
    1. To avoid rendering a list if it should be hidden

    For example, if you try to conditionally check if the user is to be shown or hidden

    <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>
    
  • Question 12

    Why do you need to use key attribute on for directive?

    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 in v-for iteration. An ideal value for key would be the unique id of each item.

    Let us take an example usage,

    {{item.name}}
    

    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.

  • Question 13

    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 'todos' trigger a view update,

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

    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()
    4. map()
    5. reduce()
    6. find()
    7. includes()
    8. every()
    9. some()
    10. indexOf()
    11. join()

    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.

  • Question 15

    What are the caveats of array changes detection?

    Vue cannot detect changes for the array in the below two cases,

    1. When you directly set an item with the index,For example,
    vm.todos[indexOfTodo] = newTodo
    
    1. When you modify the length of the array, For example,
    vm.todos.length = todosLength
    

    You can overcome both the caveats using set and splice 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)
    
Get LinkedIn Premium at Rs 399