Vue.js interview questions part 2/Vue.js Interview Questions and Answers for Freshers & Experienced

What are state preservation rules in hot reloading?

Below are the state preservation rules in hot reloading,

1. When editing the <template> of a component, instances of the edited component will re-render in place, preserving all current private state.
2. When editing the <script> part of a component, instances of the edited component will be destroyed and re-created in place.
3. When editing the <style> hot reload operates on its own via vue-style-loader without affecting application state.

What is the default behavior of hot reloading?

Hot Reload is always enabled except below situations:

1. webpack target is node (SSR)
2. webpack minifies the code
3. process.env.NODE_ENV === 'production'

What is hot reloading in vue loader?

Hot reloading is not about reloading the page when you edit any .vue file. Instead, when you edit a *.vue file, all instances of that component will be swapped in without reloading the page. It improves the development experience when you are tweaking the templates or styling of your components.

Can I use runtime builds for all templates?

No, templates (or any Vue-specific HTML) are ONLY allowed in .vue files and render functions are required in other cases.

Is CSS modules supported in Vuejs?

Yes, vue-loader provides first-class integration with CSS Modules as an alternative for simulated scoped CSS.

How do you style dynamic generated content using scoped css?

The scoped css style doesn't impact v-html directive's dynamically generated content. In this case, you can use deep selectors to solve this styling issue.

Is parent styles leaked into child components in scoped css?

The parent component's styles will not leak into child components. But a child component's root node will be affected by both the parent's scoped CSS and the child's scoped CSS. i.e, your child component's root element has a class that also exists in the parent component, the parent component's styles will leak to the child. Anyway this is by design so that the parent can style the child root element for layout purposes.

How do you work with preprocessors using vue loader?

Vue-loader will automatically infer the proper loaders to use based on the lang attribute of a language block and the rules defined in webpack config. You can use pre-processors such as SASS,LESS, Stylus and PostCSS using vuejs loader.

What are asset url transform rules?

Below are the list of Asset URL transform rules

1. Absolute path: If the URL is an absolute path (for example, /images/loader.png)then it will be preserved as-is.
2. Relative path: If the URL starts with . (for example, ./images/loader.png) then it will be interpreted as a relative module request and resolved based on the folder structure on your file system.
3. URLs starts with ~ symbol: If the URL starts with ~ symbol(for example, ./some-node-package/loader.png) then it is interpreted as a module request. This way it can reference assets inside node modules too.
4. URLs starts with @ symbol: If the URL starts with @ symbol then it is interpreted as a module request. This is useful if your webpack config has an alias for @, which by default points to /src path.

How do you configure vue loader in webpack?

Vue Loader's configuration is a bit different from other loaders by adding Vue Loader's plugin to your webpack config. The vue loader plugin is required for cloning any other rules(js and css rules) defined and applying them to the corresponding language blocks(<script> and <style>) in .vue files.

For example, the simple demonistration of webpack configuration for vue loader would be as below,

// webpack.config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
mode: 'development',
module: {
rules: [
{
test: /.vue$/,
loader: 'vue-loader'
},
// this will apply to both plain `.js` files and `<script>` blocks in `.vue` files
{
test: /.js$/,
loader: 'babel-loader'
},
// this will apply to both plain `.css` files and `<style>` blocks in `.vue` files
{
test: /.css$/,
use: [
'vue-style-loader',
'css-loader'
]
}
]
},
plugins: [
// make sure to include the plugin for cloning and mapping them to respective language blocks
new VueLoaderPlugin()
]
}

How do you access parent instance?

The $parent object refers to the immediate outer scope. The parent will be accessible as this.$parent for the child, and the child will be pushed into the parent’s $children array. It establishes a parent-child relationship between the two instances(parent and child). You can access parent data and properties similar to $root.

What is the purpose of renderError?

When the default render function encounters an error then you can use rennderError as an alternative render output. The error will be passed to renderError as the second argument.

The example usage of renderError is as below,

new Vue({
render (h) {
throw new Error('An error')
},
renderError (h, err) {
return h('div', { style: { color: 'red' }}, err.stack)
}
}).$mount('#app')

How can you redirect to another page in Vue.js?

In Vue.js, if you are using vue-router, you should use router.go(path) to navigate to any particular route. You can access the router from within a component using this.$router. router.go() changed in Vue.js 2.0. You can use router.push({ name: "yourroutename"}) or just router.push("yourroutename") now to redirect.

List out top 10 organizations using Vuejs?

Below are the top 10 organizations using VueJS for their applications or products,

1. Facebook - Used on marketing side of its Newsfeed
2. Netflix - Used in two internal apps for building movie streaming interfaces
3. Adobe - Used for Portfolio, a custom website builder designed to help users showcase their creative work
4. Xiaomi - Used for products where it sells from consumer electronics to software
5. Alibaba - Provide their apps an excellent experience to its customers
6. WizzAir - A budget airline WizzAir used for their customers user interface
7. EuroNews
8. Laracasts
9. GitLab
10. Laracasts

What is the purpose of vuejs once directive?

If you want to render a lot of static content then you need to make sure it only evaluated once and then cached thereafter. In this case, you can use v-once directive by wrapping at the root level.

The example usage of v-once directive would be as below,

Vue.component('legal-terms', {
template: `
<div v-once>
<h1>Legal Terms</h1>
... a lot of static content goes here...
</div>
`
})

How do you force update?

It is extremely rare situation of having to manually force an update despite the fact that no reactive data has changed. i.e, To force the Vue instance to re-render manually. You can do it force update using vm.$forceUpdate() API method.

How do you use various CDNs?

VueJS is available in jsdelivr, unpkg and cdnjs etc CDNs. Normally you can use them for prototyping or learning purposes.

For example, you can use them using jsdelivr with latest versions as below,

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.7/dist/vue.js"></script>
You can use it for native ES modules as below,

<script type="module">
import Vue from 'https://cdn.jsdelivr.net/npm/vue@2.6.7/dist/vue.esm.browser.js'
</script>

What is the browser support of VueJS?

It supports all ECMAScript5 complaint browsers as mentioned in this url. VueJS doesn't support IE8 browser and below, because it uses ECMAScript 5 features that are un-shimmable(require support from the underlying JS engine) in IE8.

What is Dev Tools and its purpose?

DevTools is a browser extension allowing you to inspect and debug your Vue applications in a more user-friendly interface. You can find the below extensions for different browsers or environments,

1. Chrome Extension
2. Firefox Addon
3. Standalone Electron app (works with any environment)

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);
});

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 create a component in Vue js?

Components in Vue JS are a single, independent unit of an interface. They have their own state, markup, and style.

A Vue component can be defined in four ways.

<> The first is new Vue({ /*options */ }).
<> The second is Vue.component(‘component-name’, { /* options */ }).
<> The third way is by using the local components.
<> The fourth is in the .vue files or Single File Components.

The first two ways are the standard ways to use Vue when building an application that is not a SPA (Single Page Application). The Single File Components are uses in the Single Page Application.

What is the purpose of vuejs compiler?

The compiler is is responsible for compiling template strings into JavaScript render functions.

For example, the below code snippet shows the difference of templates which need compiler and not,

// this requires the compiler
new Vue({
template: '<div>{{ message }}</div>'
})

// this does not
new Vue({
render (h) {
return h('div', this.message)
}
})

How do you configure vuejs in webpack?

You can configure vueJS in webpack using alias as below,

module.exports = {
// ...
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js' // 'vue/dist/vue.common.js' for webpack 1
}
}
}

What is the difference between full and runtime only builds?

There are two types of builds provided by VueJS,

1. Full: These are the builds that contain both the compiler and the runtime.

2. Runtime Only: These builds doesn't include compiler but the code is responsible for creating Vue instances, rendering and patching virtual DOM. These are about 6KB lighter min+gzip.

How do you make sure vue application is CSP complaint?

Some environments(Google Chrome Apps) prohibits the usage of new Function() for evaluating expressions and the full builds of vue applications depends on this feature to compile templates. Due to this reason, the full builds of VueJS application are not CSP complaint.

In this case you can use runtime-only builds with Webpack + vue-loader or Browserify + vueify technology stack through which templates will be precompiled into render functions. This way you can make sure VueJS applications are 100% CSP complaint.

What are recursive components?

The Components that can recursively invoke themselves in their own template are known as recursive components.

Vue.component('recursive-component', {
template: `<!--Invoking myself!-->
<recursive-component></recursive-component>`
});
Recursive components are useful for displaying comments on a blog, nested menus, or basically anything where the parent and child are the same, eventhough with different 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.

Let's create a x-template for simple use case as below,

<script type="text/x-template" id="script-template">
<p>Welcome to X-Template feature</p>
</script>
Now you can define the template using reference id,

Vue.component('x-template-example', {
template: '#script-template'
})

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.

<my-component inline-template>
<div>
<h1>Inline templates</h1>
<p>Treated as component component owne content</p>
</div>
</my-component>
Note: Even though this inline-templates gives more flexibility for template authoring, it is recommended to define template using template property or tag inside .vue component.

What is the structure of async component factory?

Async component factory is useful to resolve the component asynchronously. The async component factory can return an object of the below format.

const AsyncComponent = () => ({
// The component to load (should be a Promise)
component: import('./MyComponent.vue'),
// A component to use while the async component is loading
loading: LoadingComponent,
// A component to use if the load fails
error: ErrorComponent,
// Delay before showing the loading component. Default: 200ms.
delay: 200,
// The error component will be displayed if a timeout is
// provided and exceeded. Default: Infinity.
timeout: 3000
})

What is the requirement of local registration in Vue.js?

In Vue.js, local registration is required when the global registration seems not ideal. For example, suppose you are using a build system like Webpack and globally registering all components. In that case, even if we stop using a component, it could still be included in your final build. This unnecessarily increases the amount of JavaScript your users have to download. In these cases, it is better to define your components as plain JavaScript objects as follows:

var ComponentA = {/*.......*/}
var ComponentB = {/*.......*/}
var ComponentC = {/*.......*/}
After that define the components you would like to use in a components option as follows:

new Vue({
el: '#app',
components: {
'component-a': ComponentA,
'component-b': ComponentA
}
})

What are the different supported System Modifier Keys in Vue.js?

Vue.js supports the following modifiers to trigger mouse or keyboard event listeners when we press the corresponding keys. The list of supported System Modifier Keys is:

.ctrl
.alt
.shift
.meta
See the following example of a control modifier with the click event.

Example:

<!-- Ctrl + Click -->
<div @click.ctrl="doAction">Do some action here</div>

Give an example to demonstrate how do you define custom key modifier aliases in Vue.js?

We can define custom key modifier aliases via the global config.keyCodes. Following are some guidelines for the properties:

We can't use camelCase. Instead, we should use a kebab-case with double quotation marks.
We can define multiple values in an array format.


See the example:

Vue.config.keyCodes = {
f1: 112,
"media-play-pause": 179,
down: [40, 87]
}

What are the array detection non-mutation methods in Vue.js?

The array detection non-mutation methods in Vue.js are the methods that do not mutate the original array but always return a new array.

Following is a list of the non-mutation methods:

1. filter()
2. concat()
3. slice()
For example, let's take a todo list where it replaces the old array with new one based on status filter:

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

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.

Let's see the example usage of it,

<!-- Inactive components will be cached! -->
<keep-alive>
<component v-bind:is="currentTabComponent"></component>
</keep-alive>
When there are multiple conditional children, it requires that only one child is rendered at a time.

<!-- multiple conditional children -->
<keep-alive>
<comp-a v-if="a > 1"></comp-a>
<comp-b v-else></comp-b>
</keep-alive>

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 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 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 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,

Stateless: It doesn’t keep any state by itself
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) {
// ...
}
})

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

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

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

<div v-avatar="{ width: 500, height: 400, url: 'path/logo', text: 'Iron Man' }"></div>
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"
})

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.

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>

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.

How many types of the directive are used in Vue.js?

The following types of directives are used in Vue.js:

1. General Directives
2. Literal Directives
3. Empty Directives
4. Custom Directives

Why is it recommended not to use v-if and v-for directives together on the same element in Vue.js?

It is recommended not to use v-if and v-for directives together on the same element because the v-for directive has a higher priority than v-if directive. If you use both directives together, then there are two common cases where this may be tempting:

1. When you have to filter items in a list (e.g. v-for="user in users" v-if="user.isActive"). In these cases, replace users with a new computed property that returns your filtered list (e.g., activeUsers).

2. To avoid rendering a list if it should be hidden (e.g. v-for="user in users" v-if="shouldShowUsers"). In these cases, move the v-if to a container element (e.g., ul, ol).

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.

How do you use mixins in CLI?

Using Vue CLI, mixins can be specified anywhere in the project folder but preferably within /src/mixins for ease of access. Once these mixins are created in a .js file and exposed with the export keyword, they can be imported in any component with the import keyword and their file paths.

What are plugins and their various services?

lugins 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

Search
R4R Team
R4R provides Vue.js Freshers questions and answers (Vue.js Interview Questions and Answers) .The questions on R4R.in website is done by expert team! Mock Tests and Practice Papers for prepare yourself.. Mock Tests, Practice Papers,Vue.js interview questions part 2,Vue.js Freshers & Experienced Interview Questions and Answers,Vue.js Objetive choice questions and answers,Vue.js Multiple choice questions and answers,Vue.js objective, Vue.js questions , Vue.js answers,Vue.js MCQs questions and answers Java, C ,C++, ASP, ASP.net C# ,Struts ,Questions & Answer, Struts2, Ajax, Hibernate, Swing ,JSP , Servlet, J2EE ,Core Java ,Stping, VC++, HTML, DHTML, JAVASCRIPT, VB ,CSS, interview ,questions, and answers, for,experienced, and fresher R4r provides Python,General knowledge(GK),Computer,PHP,SQL,Java,JSP,Android,CSS,Hibernate,Servlets,Spring etc Interview tips for Freshers and Experienced for Vue.js fresher interview questions ,Vue.js Experienced interview questions,Vue.js fresher interview questions and answers ,Vue.js Experienced interview questions and answers,tricky Vue.js queries for interview pdf,complex Vue.js for practice with answers,Vue.js for practice with answers You can search job and get offer latters by studing r4r.in .learn in easy ways .