FrontendDeveloper.in

Vue.js Interview Questions

  • Question 31

    How do you implement model on custom input components?

    The custom events can also be used to create custom inputs that work with v-model. The <input> inside the component must follow below rules,

    1. Bind the value attribute to a value prop
    2. On input, emit its own custom input event with the new value.

    Let's take a custom-input component as an example,

    Vue.component('custom-input', {
    props: ['value'],
    template: `
    <input
    v-bind:value="value"
    v-on:input="$emit('input', $event.target.value)"
    />
    `
    })
    

    Now you can use v-model with this component,

    <custom-input v-model="searchInput"></custom-input>
    
  • Question 32

    What are slots?

    Vue implements a content distribution API using the <slot> 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: `
    <strong>Error!</strong>
    <slot></slot>
    `
    })
    

    Now you can insert dynamic content as below,

    <alert>
    There is an issue with in application.
    
  • Question 33

    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,

    <component-a></component-a>
    <component-b></component-b>
    <component-c></component-c>
    

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

  • Question 34

    Why do you need local registration?

    Due to global registration, even if you don't use the component it could still be included in your final build. So it will create unnecessary javascript in the application. This can be avoided using local registration with the below steps,

    1. First you need to define your components as plain JavaScript objects
    var ComponentA = { /* ... */ }
    var ComponentB = { /* ... */ }
    var ComponentC = { /* ... */ }
    

    Locally registered components will not be available in sub components. In this case, you need to add them in components section

    var ComponentA = { /* ... */ }
    
    var ComponentB = {
    components: {
    'component-a': ComponentA
    },
    // ...
    }
    
    1. You can use the components in the components section of the vue instance,
    new Vue({
    el: '#app',
    components: {
    'component-a': ComponentA,
    'component-b': ComponentB
    }
    })
    
  • Question 35

    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
    )
    })
    
  • Question 36

    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.

  • Question 37

    What is the data flow followed by props?

    All props follows a one-way-down binding between the child property and the parent one. i.e, When the parent property is updated then that latest prop value will be passed down to the child, but not the otherway(child to parent) around. The child component should not mutate the prop otherwise it throws a warning in the console. The possible mutation cases can be solved as below,

    1. When you try to use parent prop as initial value for child property:

    In this case you can define a local property in child component and assign parent value as initial value

    props: ['defaultUser'],
    data: function () {
    return {
    username: this.defaultUser
    }
    }
    
    1. When you try to transform the parent prop:

    You can define a computed property using the prop's value,

    props: ['environment'],
    computed: {
    localEnvironment: function () {
    return this.environment.trim().toUpperCase()
    }
    }
    
  • Question 38

    What are non prop attributes?

    A non-prop attribute is an attribute that is passed to a component, but does not have a corresponding prop defined.

    For example, If you are using a 3rd-party custom-input component that requires a data-tooltip attribute on the input then you can add this attribute to component instance,

    <custom-input data-tooltip="Enter your input" />
    

    If you try to pass the props from parent component the child props with the same names will be overridden. But props like class and style are exception to this, these values will be merged in the child component.

    <!-- Child component -->
    <input type="date" class="date-control">
    
    <!-- Parent component -->
    <custom-input class="custom-class" />
    
  • Question 39

    Describe about validations available for props?

    Vue provides validations such as types, required fields, default values along with customized validations. You can provide an object with validation requirements to the value of props as below,

    Let's take an example of user profile Vue component with possible validations,

    Vue.component('user-profile', {
    props: {
    // Basic type check (`null` matches any type)
    age: Number,
    // Multiple possible types
    identityNumber: [String, Number],
    // Required string
    email: {
    type: String,
    required: true
    },
    // Number with a default value
    minBalance: {
    type: Number,
    default: 10000
    },
    // Object with a default value
    message: {
    type: Object,
    // Object or array defaults must be returned from
    // a factory function
    default: function () {
    return { message: 'Welcome to Vue' }
    }
    },
    // Custom validator function
    location: {
    validator: function (value) {
    // The value must match one of these strings
    return ['India', 'Singapore', 'Australia'].indexOf(value) !== -1
    }
    }
    }
    })
    
  • Question 40

    How do you customize model directive for a component?

    The v-model directive on a component uses value as the prop and input as the event, but some input types such as checkboxes and radio buttons may need to use the value attribute for a server side value. In this case, it is preferred to customize model directive.

    Let's take an example of checkbox component,

    Vue.component('custom-checkbox', {
    model: {
    prop: 'checked',
    event: 'change'
    },
    props: {
    checked: Boolean
    },
    template: `
    <input
    type="checkbox"
    v-bind:checked="checked"
    v-on:change="$emit('change', $event.target.checked)"
    >
    `
    })
    

    Now you can use v-model on this customized component as below,

    <custom-checkbox v-model="selectFramework"></custom-checkbox>
    

    The selectFramework property will be passed to the checked prop and same property will be updated when custom checkbox component emits a change event with a new value.

  • Question 41

    What are the possible ways to provide transitions?

    There are many ways Vue provides transition effects when items are inserted, updated, or removed from the DOM.

    Below are the possible ways,

    1. Automatically apply classes for CSS transitions and animations
    2. Integrate 3rd-party CSS animation libraries. For example, Animate.css
    3. Use JavaScript to directly manipulate the DOM during transition hooks
    4. Integrate 3rd-party JavaScript animation libraries. For example, Velocity.js
  • Question 42

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

    What are the steps to use vue router and give an example?

    It is easy to integrate vue router in the vue application.

    Let us see the example with step by step instructions.

    Step 1: Configure router link and router view in the template

    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
    
    <h1>Welcome to Vue routing app!</h1>
    <!-- use router-link component for navigation using `to` prop. It rendered as an `<a>` tag -->
    <router-link to="/home">Home</router-link>
    <router-link to="/services">Services</router-link>
    <!-- route outlet in which component matched by the route will render here -->
    <router-view></router-view>
    

    Step 2: Import Vue and VueRouter packages and then apply router

    import Vue from 'vue';
    import VueRouter from 'vue-router';
    
    Vue.use(VueRouter)
    

    Step 3: Define or import route components.

    const Home = { template: '<div>Home</div>' }
    const Services = { template: '<div>Services</div>' }
    

    Step 4: Define your route where each one maps to a component

    const routes = [
    { path: '/home', component: Home },
    { path: '/services', component: Services }
    ]
    

    Step 5: Create the router instance and pass the routes option

    const router = new VueRouter({
    routes // short for `routes: routes`
    })
    

    Step 6: Create and mount the root instance.

    const app = new Vue({
    router
    }).$mount('#app')
    

    Now you are able to navigate different pages(Home, Services) with in Vue application.

  • Question 44

    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 }
    ]
    })
    
  • Question 45

    How to make router param changes as reactive?

    When you navigate from one URL to other(mapped with a single component) using routes with params then the same component instance will be reused. Even though it is more efficient than destroying the old instance and then creating a new one, the lifecycle hooks of the component will not be called.

    This problem can be solved using either of the below approaches,

    1. Watch the $route object:
    const User = {
    template: '<div>User {{ $route.params.name }} </div>',
    watch: {
    '$route' (to, from) {
    // react to route changes...
    }
    }
    }
    
    1. Use beforeRouteUpdate navigation guard: This is only available since 2.2 version.
    const User = {
    template: '<div>User {{ $route.params.name }} </div>',
    beforeRouteUpdate (to, from, next) {
    // react to route changes and then call next()
    }
    }
    

    Note that the beforeRouteEnter guard does NOT have access to this. Instead you can pass a callback to next to access the vm instance.

Get LinkedIn Premium at Rs 399