FrontendDeveloper.in

Vue.js Interview Questions

  • Question 61

    What are the merging strategies in mixins?

    When a mixin and the component itself contain overlapping options, the options will be merged based on some strategies.

    1. The data objects undergo a recursive merge, with the component's data taking priority over mixins in cases of overlapping or conflicts.
    var mixin = {
    data: function () {
    return {
    message: 'Hello, this is a Mixin'
    }
    }
    }
    new Vue({
    mixins: [mixin],
    data: function () {
    return {
    message: 'Hello, this is a Component'
    }
    },
    created: function () {
    console.log(this.$data); // => { message: "Hello, this is a Component'" }
    }
    })
    
    1. The Hook functions which are overlapping merged into an array so that all of them will be called. Mixin hooks will be called before the component's own hooks.
    const myMixin = {
    created(){
    console.log("Called from Mixin")
    }
    }
    
    new Vue({
    el: '#root',
    mixins: [myMixin],
    created(){
    console.log("Called from Component")
    }
    })
    
    // Called from Mixin
    // Called from Component
    
    1. The options that expect object values(such as methods, components and directives) will be merged into the same object. In this case, the component's options will take priority when there are conflicting keys in these objects.
    var mixin = {
    methods: {
    firstName: function () {
    console.log('John')
    },
    contact: function () {
    console.log('+65 99898987')
    }
    }
    }
    
    var vm = new Vue({
    mixins: [mixin],
    methods: {
    lastName: function () {
    console.log('Murray')
    },
    contact: function () {
    console.log('+91 893839389')
    }
    }
    })
    
    vm.firstName() // "John"
    vm.lastName() // "Murray"
    vm.contact() // "+91 893839389"
    
  • Question 62

    What are custom options merging strategies?

    Vue uses the default strategy which overwrites the existing value while custom options are merged. But if you want a custom option merged using custom login then you need to attach a function to Vue.config.optionMergeStrategies

    For the example, the structure of myOptions custom option would be as below,

    Vue.config.optionMergeStrategies.myOption = function (toVal, fromVal) {
    // return mergedVal
    }
    

    Let's take below Vuex 1.0 merging strategy as an advanced example,

    const merge = Vue.config.optionMergeStrategies.computed
    Vue.config.optionMergeStrategies.vuex = function (toVal, fromVal) {
    if (!toVal) return fromVal
    if (!fromVal) return toVal
    return {
    getters: merge(toVal.getters, fromVal.getters),
    state: merge(toVal.state, fromVal.state),
    actions: merge(toVal.actions, fromVal.actions)
    }
    }
    
  • Question 63

    What are custom directives?

    Custom Directives are tiny commands that you can attach to DOM elements. They are prefixed with v- to let the library know you're using a special bit of markup and to keep syntax consistent. They are typically useful if you need low-level access to an HTML element to control a bit of behavior.

    Let's create a custom focus directive to provide focus on specific form element during page load time,

    // Register a global custom directive called `v-focus`
    Vue.directive('focus', {
    // When the bound element is inserted into the DOM...
    inserted: function (el) {
    // Focus the element
    el.focus()
    }
    })
    

    Now you can use v-focus directive on any element as below,

    <input v-focus>
    
  • Question 64

    How do you register directives locally?

    You can also register directives locally(apart from globally) using directives option in component as below,

    directives: {
    focus: {
    // directive definition
    inserted: function (el) {
    el.focus()
    }
    }
    }
    

    Now you can use v-focus directive on any element as below,

    <input v-focus>
    
  • Question 65

    What are the hook functions provided by directives?

    A directive object can provide several hook functions,

    1. bind: This occurs once the directive is attached to the element.
    2. inserted: This hook occurs once the element is inserted into the parent DOM.
    3. update: This hook is called when the element updates, but children haven't been updated yet.
    4. componentUpdated: This hook is called once the component and the children have been updated.
    5. unbind: This hook is called only once when the directive is removed.

    Note: There are several arguments that can be passed to the above hooks.

  • Question 66

    What are the directive Hook Arguments?

    All the hooks have el, binding, and vnode as arguments. Along with that, update and componentUpdated hooks expose oldVnode, to differentiate between the older value passed and the newer value. Below are the arguments passed to the hooks,

    1. el: The element the directive is bound to and it can be used to directly manipulate the DOM.
    2. binding: An object containing the following properties.
    3. name: The name of the directive, without the v- prefix.
    4. value: The value passed to the directive. For example in v-my-directive="1 + 1", the value would be 2.
    5. oldValue: The previous value, only available in update and componentUpdated. It is available whether or not the value has changed.
    6. expression: The expression of the binding as a string. For example in v-my-directive="1 + 1", the expression would be "1 + 1".
    7. arg: The argument passed to the directive, if any. For example in v-my-directive:foo, the arg would be " foo".
    8. modifiers: An object containing modifiers, if any. For example in v-my-directive.foo.bar, the modifiers object would be { foo: true, bar: true }.
    9. vnode: The virtual node produced by Vue's compiler.
    10. oldVnode: The previous virtual node, only available in the update and componentUpdated hooks.

    The arguments can be represented diagrammatically across the hooks as below,

    custom-directives

  • Question 67

    How do you pass multiple values to a directive?

    A directive can take any valid javascript expression. So if you want to pass multiple values then you can pass in a JavaScript object literal.

    Let's pass object literal to an avatar directive as below

    Now let us configure avatar directive globally,

    Vue.directive('avatar', function (el, binding) {
    console.log(binding.value.width) // 500
    console.log(binding.value.height)  // 400
    console.log(binding.value.url) // path/logo
    console.log(binding.value.text)  // "Iron Man"
    })
    
  • Question 68

    What is function shorthand in directive hooks?

    In few cases, you may want the same behavior on bind and update hooks irrespective of other hooks. In this situation you can use function shorthand,

    Vue.directive('theme-switcher', function (el, binding) {
    el.style.backgroundColor = binding.value
    })
    
  • Question 69

    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.

  • Question 70

    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.

    Let's take an example of simple Div markup and corresponding render function. The HTML markup can be written in template tag as below,

    <template>
    </template>
    

    and the compiled down or explicit render function would appear as below,

    render: function (createElement) {
    return createElement('div', {
    'class': {
    'is-rounded': this.isRounded
    }
    }, [
    createElement('p', 'Welcome to Vue render functions')
    ]);
    }
    

    Note: The react components are built with render functions in JSX.

  • Question 71

    Explain the structure of createElement with arguments?

    The createElement accepts few arguments to use all the template features.

    Let us see the basic structure of createElement with possible arguments,

    // @returns {VNode}
    createElement(
    // An HTML tag name, component options, or async function resolving to one of these.
    // Type is {String | Object | Function}
    // Required.
    'div',
    
    // A data object corresponding to the attributes you would use in a template.
    // Type is {Object}
    // Optional.
    {
    // Normal HTML attributes
    attrs: {
    id: 'someId'
    },
    // Component props
    props: {
    myProp: 'somePropValue'
    },
    // DOM properties
    domProps: {
    innerHTML: 'This is some text'
    },
    // Event handlers are nested under `on`
    on: {
    click: this.clickHandler
    },
    // Similar to `v-bind:style`, accepting either a string, object, or array of objects.
    style: {
    color: 'red',
    fontSize: '14px'
    },
    // Similar to `v-bind:class`, accepting either a string, object, or array of strings and objects.
    class: {
    className1: true,
    className2: false
    }
    // ....
    },
    
    // Children VNodes, built using `createElement()`, or using strings to get 'text VNodes'.
    // Type is {String | Array}
    // Optional.
    [
    'Learn about createElement arguments.',
    createElement('h1', 'Headline as a child virtual node'),
    createElement(MyComponent, {
    props: {
    someProp: 'This is a prop value'
    }
    })
    ]
    )
    

    See details of the date object in official doc.

  • Question 72

    How can you write duplicate virtual nodes in a component?

    All virtual nodes(VNodes) in the component tree must be unique.i.e, You can't write duplicated nodes in a straightforward way. If you want to duplicate the same element/component many times then you should use factory function.

    The below render function is invalid where you are trying to duplicate h1 element 3 times,

    render: function (createElement) {
    var myHeadingVNode = createElement('h1', 'This is a Virtual Node')
    return createElement('div', [
    myHeadingVNode, myHeadingVNode, myHeadingVNode
    ])
    }
    

    You can make duplicates with factory function,

    render: function (createElement) {
    return createElement('div',
    Array.apply(null, { length: 3 }).map(function () {
    return createElement('h1', 'This is a Virtual Node')
    })
    )
    }
    
  • Question 73

    List down the template equivalents in render functions?

    VueJS provides proprietary alternatives and plain javascript usage for the template features.

    Let's list down them in a table for comparison,

    TemplatesRender function
    Conditional and looping directives: v-if and v-forUse JavaScript's if/else and map concepts
    Two-way binding: v-modelApply own JS logic with value binding and event binding
    Capture Event modifiers: .passive, .capture, .once and .capture.once or .once.capture&, !, ~ and ~!
    Event and key modifiers: .stop, .prevent, .self, keys(.enter, .13) and Modifiers Keys(.ctrl, .alt, .shift, .meta)Use javascript solutions: event.stopPropagation(), event.preventDefault(), if (event.target !== event.currentTarget) return, if (event.keyCode !== 13) return and if (!event.ctrlKey) return
    Slots: slot attributesRender functions provide this.$slots and this.$scopedSlots instance properties
  • Question 74

    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

    You need to define functional: true to make it functional. Let's take an example of functional components,

    Vue.component('my-component', {
    functional: true,
    // Props are optional
    props: {
    // ...
    },
    // To compensate for the lack of an instance,
    // we are now provided a 2nd context argument.
    render: function (createElement, context) {
    // ...
    }
    })
    

    Note: The functional components are quite popular in React community too.

  • Question 75

    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).
Get LinkedIn Premium at Rs 399