Google News
logo
Vue.JS Interview Questions
Vue.js is a JavaScript framework. Vue.js it builds dynamic user interfaces and single-page applications, on top of standard HTML, CSS and JavaScript, and provides a declarative and component-based programming model that helps you efficiently develop user interfaces, be it simple or complex.

Here is a minimal example :
import { createApp } from 'vue'

createApp({
  data() {
    return {
      count: 0
    }
  }
}).mount('#app')
<div id="app">
  <button @click="count++">
    Count is: {{ count }}
  </button>
</div>​

Result : 
Count is: 0
 
The above example demonstrates the two core features of Vue :
 
Declarative Rendering : Vue extends standard HTML with a template syntax that allows us to declaratively describe HTML output based on JavaScript state.
 
Reactivity : Vue automatically tracks JavaScript state changes and efficiently updates the DOM when changes happen.
Vue is an independent, community-driven project. It was created by "Evan You" in 2014 as a personal side project. Today, Vue is actively maintained by a team of both full-time and volunteer members from all around the world, where Evan serves as the project lead.
The latest version of Vue (3.x) only supports browsers with native ES2015 support. This excludes IE11. Vue 3.x uses ES2015 features that cannot be polyfilled in legacy browsers, so if you need to support legacy browsers, you will need to use Vue 2.x instead.
Vue is a mature and battle-tested framework. It is one of the most widely used JavaScript frameworks in production today, with over 1.5 million users worldwide, and is downloaded close to 10 million times a month on npm.
 
Vue is used in production by renowned organizations in varying capacities all around the world, including Wikimedia Foundation, NASA, Apple, Google, Microsoft, GitLab, Zoom, Tencent, Weibo, Bilibili, Kuaishou, and many more.
Vue 3 is the current, latest major version of Vue. It contains new features that are not present in Vue 2 (most notably Composition API), and also contains breaking changes that makes it incompatible with Vue 2. Despite the differences, the majority of Vue APIs are shared between the two major versions, so most of your Vue 2 knowledge will continue to work in Vue 3.
 
In general, Vue 3 provides smaller bundle sizes, better performance, better scalability, and better TypeScript / IDE support. If you are starting a new project today, Vue 3 is the recommended choice. There are only a few reasons for you to consider Vue 2 as of now:
 
* You need to support IE11. Vue 3 leverages modern JavaScript features and does not support IE11.
 
* You are still waiting for major ecosystem projects like Nuxt or Vuetify to release stable versions for Vue 3. This is reasonable if you do not wish to use beta-stage software. However, do note there are other already stable Vue 3 component libraries such as Quasar, Naive UI and Element Plus.
 
If you intend to migrate an existing Vue 2 app to Vue 3, consult the dedicated Vue 3 Migration Guide.
 
Vue 2 has shipped a final minor release (2.7) in July 2022, which backports a selected subset of new features from Vue 3. Vue 2 has now entered maintenance mode: it will no longer ship new features, but will continue to receive critical bug fixes and security updates until the end of 2023.
Vue was created before Web Components were natively available, and some aspects of Vue's design (e.g. slots) were inspired by the Web Components model.
 
The Web Components specs are relatively low-level, as they are centered around defining custom elements. As a framework, Vue addresses additional higher-level concerns such as efficient DOM rendering, reactive state management, tooling, client-side routing, and server-side rendering.
Some of major features available with Vue.js :
 
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.
Explain the all life cycle events or hooks in Vue instance in Vue.js. / Explain the Life cycle of Vue Instance with diagram.
When a Vue instance is created in Vue.js, it goes through a series of steps after creation. First, they are created then mounted and after that destroyed at the end. In this process, it also runs functions known as life cycle hooks. These life cycle hooks allow the developers to add their own code at a specific stage.
 
Following is the list of all events or hooks a Vue instance goes through :
 
beforeCreate event: This is the first event or hook that occurs in the creation process. It facilitates developers to perform actions even before the component has been added to the DOM. We cannot access the DOM inside of this event.
 
created event : This event is used to run the code after creating the instance. It facilitates you to access the reactive data, but the mounting or rendering of templates and Virtual DOM is not completed yet.
 
beforeMount event : The beforeMount event is used to execute just before the initial render happens and after the template or render functions have been compiled. This is the rarely used event, and in most cases, you don't need to use this event.
 
mounted event : This is the most frequently used event or hook. In this event, you have full access to the reactive component, templates, and rendered DOM.
 
beforeUpdate event : This event is executed just before the data changes on the component and the update cycle's start. It runs right before the DOM is patched and re-rendered.
 
updated : This event is used to execute after the data changes on the component and the DOM re-renders. If you want to access the DOM after a property change, it is the best place to complete this action.
 
beforeDestroy : This event is used to execute just before tearing down the instance. This is the second last step of the Vue Instance life process and is the right place to clean up events or reactive subscriptions if you have to do this.
 
destroyed : This is the last step of the Vue Instance life process and used to do any last minute clean up.
 
Lifecycle Diagram of the Vue Instance :
Lifecycle
The official router of Vue.js is called Vue Router. It is by default integrated with Vue.js core and used to build Single Page Applications with Vue.js.
 
Following is the list of important features of Vue Router :
 
* Vue Router follows a modular, component-based router configuration.
* Very easy to implement.
* You can customize the Scroll Behavior.
* Provides Nested route/view mapping.
* Provides fine-grained navigation control.
* Route params, query, wildcards
* js' transition system provides View transition effects.
* Links with automatic active CSS classes.
* HTML5 history mode or hash mode, with auto-fallback in IE9.
In Vue.js, a slot is a placeholder in a child component filled with content passed from the parent component.
 
In the slot, the component is compiled in the parent's scope and then passed to the child component. So, it is not possible to use child component properties in a slot's content.
 
In Scoped slot, you can pass child component data to the parent scope and then use it in slot content.
In Vue.js, the virtual DOM is a tree-like data structure or a collection of JavaScript objects that represents DOM nodes. Vue.js manage the nodes of the virtual DOM, and that should be rendered on the page. These objects are called "virtual nodes" or VNodes.
The virtual DOM's main purpose is to make DOM manipulation faster and more efficient. It becomes very crucial when you have a lot of nodes in your DOM. In this case, updating these nodes is a very expensive task for processing power and resources required. Here, virtual DOM comes into action and makes JavaScript object significantly faster. Vue.js automatically organizes DOM updates in batches to enhance efficiency.
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>
Index v-show directive v-if directive
1. The v-if directive is used to render the element to the DOM only if the expression passes. The v-show directive is used to render all elements to the DOM and then uses the CSS display property to show/hide elements according to the expression.
2. The v-if directive also supports v-else and v-else-if directives. The v-show directive doesn't support the v-else and v-else-if directives.
3. The v-if directive has higher toggle costs since it adds or removes the DOM every time. The v-show directive has higher initial render costs.
4. The v-if directive has the advantage when it comes to initial render time. The v-show directive has a performance advantage if you have to switch on and switch off the elements frequently.
5. The v-if directive supports the tab. The v-show directive doesn't support the tab.
In Vue.js, the data is passed to child components from the parent component using a prop or a custom attribute. This custom attribute becomes a property on the child component instance. This procedure is called a one-way data flow.
 
Once the parent component updates a prop value, the child component is automatically updated. The child component can communicate back to the parent via an event, but mutating a property inside a child component should not be done. It does not affect the parent component also unless it is an object or array. When the child component instance emits an event, the parent assigns a handler to that event, and data is passed back to the parent.
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 of in, similar to javascript iterators.
 
Object usage :
<div id="object">
  <div v-for="(value, key, index) of user">
    {{ index }}. {{ key }}: {{ value }}
  </div>
</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.
The VUE-resource is a plug-in for Vue.js. This plug-in is used with Vue.js to make web requests and handle responses, in which XHMLHttpRequests or JSONP is used.
 
You can use the following yarn or npm command to install VUE-resource:
$ yarn add vue-resource  
$ npm install vue-resource   
You can install Vue.js in your project by using the following 4 methods:
 
* Yu can use CDN by including <script> tag in HTML file.
* You can install Vue.js by using Node Package Manager (NPM).
* You can install Vue.js using Bower.
* You can also use Vue-cli to setup your project.

CDN :  For prototyping or learning purposes, you can use the latest version with:
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.0/dist/vue.js"></script>
For production, we recommend linking to a specific version number and build to avoid unexpected breakage from newer versions:
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.0"></script>
If you are using native ES Modules, there is also an ES Modules compatible build:
<script type="module">
  import Vue from 'https://cdn.jsdelivr.net/npm/vue@2.7.0/dist/vue.esm.browser.js'
</script>
You can browse the source of the NPM package at cdn.jsdelivr.net/npm/vue.
 
Vue is also available on unpkg and cdnjs (cdnjs takes some time to sync so the latest release may not be available yet).
 
Make sure to read about the different builds of Vue and use the production
version in your published site, replacing vue.js with vue.min.js. This is a smaller build optimized for speed instead of development experience.
 
NPM : NPM is the recommended installation method when building large scale applications with Vue. It pairs nicely with module bundlers such as Webpack or Browserify. Vue also provides accompanying tools for authoring Single File Components.
# latest stable
$ npm install vue
CLI : Vue provides an official CLI for quickly scaffolding ambitious Single Page Applications. It provides batteries-included build setups for a modern frontend workflow. It takes only a few minutes to get up and running with hot-reload, lint-on-save, and production-ready builds. See the Vue CLI docs for more details.

Source : v2.vuejs.org
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>
List of advantages of using Vue.js :
 
Very Small In Size :  One of Vue.js' biggest advantages is that it is very small in size. This exciting JavaScript plug-in is only 18-21KB, so you can download and use it very easily in no time.
 
Easy to Understand and Use : The framework of Vue.js is very easy to understand, and it id one of the reasons for the popularity of this framework. The users can easily add Vue.js to their web project because of its simple structure and develop applications.
 
Flexible in nature : The flexible nature of Vue.js also makes it easy to understand for the developers of React.js, Angular.js, and any other new JavaScript framework. It provides a lot of flexibility to use virtual nodes to write HTML files, JavaScript files, and pure JavaScript files.
 
Components : You can create reusable custom elements in Vue.js applications.
 
Virtual DOM : Vue.js 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.
 
Two-Way Communication : Vue.js provides two-way communications with its MVVM architecture that makes it very easy to handle HTML blocks.

Simple Integration with Existing Applications : Vue.js framework can be integrated with the existing applications very easily. Vue.js has a lot of components for everything. You can integrate it with any application that is written in JavaScript.

Easy & comprehensive documentation : The documentation of Vue.js is very easy and comprehensive so that developers can develop applications or web pages, only having little knowledge about HTML.
List of some websites using Vue.js on parts of their projects and applications :
 
* Adobe
* Facebook
* Netflix
* Alibaba
* Laracast
* Behance
* Gitlab
* Euronews
* Codeship
* Livestorm
* Xiaomi
* Wizzair
* Grammarly etc,.
In one-way data binding (one-way data flow), the view (UI) part of the application does not update automatically. In this model, when the data Model is changed, you need to write some custom code to make it updated every time after the change. The v-bind directive is used for one-way data flow or binding in Vue.js.
 
On the other hand, in two-way data binding, the view (UI) part of the application is automatically updated when the data Model is changed. The v-model directive is used for two way data binding in Vue.js.
The v-model directive is used to create Two-Way Bindings in Vue js. In Two-Way Bindings, data or model binds with DOM, and Dom binds back to the model.
 
Let's see an example to demonstrate how Two-Way Bindings is implemented.
<div id="app">  
  {{message}}  
  <input v-model="message">  
</div>  
<script type="text/javascript">  
  var message = 'Vue.js is rad';  
  new Vue({ el: '#app', data: { message } });  
</script>
In Vue js filters are used to transform the output that are going to rendered on browser.

A Vue.js filter is essentially a function that takes a value, processes it, and then returns the processed value. In the markup it is denoted by a single pipe (|) and can be followed by one or more arguments:
<element directive="expression | filterId [args...]"></element>
In Vue 2.0, there are no built-in filters are availables, however you are free to create your own filters.
Vue.filter() method is used to create and register a custom filter in Vue js. Vue.filter() method takes two parameters a filterId that is usnique name to filter that you going to create and a filter function that takes a value as the argument and returns the transformed value.

Vue.filter('reverse', function (value) {
  return value.split('').reverse().join('')
})
Virtual DOM in Vue is a JavaScript object that represents the Document Object Model (DOM). The application updates the Virtual DOM instead of the DOM directly. So, it minimizes the updating cost of the real DOM as it is computationally expensive. Virtual DOM offers the ability to control the timing at which the Virtual DOM is rendered. Virtual DOM will just maintain the state of the data without re-rendering until you choose it. Virtual DOM also offers the ability to optimize the performance of your web applications by minimizing the number of times the DOM has to be updated.
Vue.js implements a content distribution API using the 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: `
    <div class="alert-box">
      <strong>Error!</strong>
      <slot></slot>
    </div>
  `
})
Now you can insert dynamic content as below,
<alert>
  There is an issue with in application.
</alert>
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.
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.
 
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.
In Vue.js, every component instance has its own isolated scope. So, you cannot directly reference parent data in a child component's template.
 
Props are used to pass down data to the child components. Props are custom attributes. You can register on a component. When a value is passed to a prop attribute, it becomes a property on that component instance.
Vue.component('blog-post', {  
  // camelCase in JavaScript  
  props: ['postTitle'],  
  template: '<h3>{{ postTitle }}</h3>'  
})​
 
VueX is a state management pattern and library for the Vue.js application. It is used as a centralized store for all the different components in the Vue.js application.

Vuex provides some rules to ensure that the state can only be mutated in a predictable fashion. You can get a lot of additional features by integrating Vuex with the official devtool extension of Vue.js.
You can install vuex using npm or yarn as below,
npm install vuex --save
(or)
yarn add vuex
In a module system, you must explicitly install Vuex via Vue.use()
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
(OR)
 
You can also install it using CDN links such as unpkg.cpm which provides NPM-based CDN links. Just include vuex after Vue and it will install itself automatically.
<script src="https://unpkg.com/vue.js"></script>
<script src="https://unpkg.com/vuex.js"></script>
Note: You can use a specific version/tag via URLs like https://unpkg.com/vuex@2.0.0. If you don't mention any version then it will point to latest version.
Vuex enforces below high-level principles,
 
* The Application-level state need to be centralized in the store
* The state should be mutated by committing mutations only(i.e, for synchronous transactions)
* The actions should be used for asynchronous transactions.
By default, actions, mutations and getters inside modules are still registered under the global namespace. Because of that multiple modules react to the same mutation/action type.
If you keep all state of our application in a single big state, the store can get really bloated. To solve this problem, Vuex allows us to divide our store into modules. Here, each module can contain its own state, mutations, actions, getters, and even nested modules.
 
Let's take an example with multiple modules, configuring them in vuex and accessing different modules,
const moduleOne = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleTwo = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const store = new Vuex.Store({
  modules: {
    one: moduleOne,
    two: moduleTwo
  }
})

store.state.one // -> `moduleOne's state
store.state.two // -> `moduleTwo's state
Yes, we can call Rest API from Vue.js. There are several HTTP libraries that can used to call REST Api's from Vue.js. One of the popular libraries is Axios. It is very simple to use and lightweight. You can include it in your project by using 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);  
            });​
  
You can create a project by using the following command:
vue init webpack myproject  
To run your project, run the following command:
npm run build  
After executing the above command, copy index.html and /dist/ folder into your website root directory, and your project will be deployed.
The Vue-loader is a loader module for webpack in Vue.js that is used to write single file components using the .vue file format.
 
The single-file component contains three sections called template, script, and style. The webpack can extract and process each section using separate loader modules such as the SASS or SCSS loaders. The vue-loader module makes static assets to be treated as module dependencies and enables processing using webpack loaders.
The following example which demonstrates how to handle Events in Vue.js :
 
HTML Code :
<div id="app">  
  Name: <input type="text" v-model="name">  
  <button v-on:click="myClickHandler">Say Hello button</button>  
</div>​

 

JS Code :
var myViewModel = new Vue({  
  el: '#app',  
  data: my Model,  
  // A click handler inside methods  
  methods: {  
    ClickHandler: function(e) {  
      alert("Hello " + this.name);  
    }  
  }  
 });  
Vue cannot detect changes for the array in the below two cases,
 
* When you directly set an item with the index,For example,
vm.todos[indexOfTodo] = newTodo
* 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)
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.user.email = john@email.com // `vm.user.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
})
Mixin support is a feature that allows code reuse between components in a Vue.js application and a software composition tool.
 
A mixin is a JavaScript object that can contain any option that a component can contain. All mixin content is merged with a component’s options when that component uses a mixin.
 
Mixins help with following the DRY (don’t repeat yourself) principle. A mixin can even be applied globally to every component instance. In that case, it’s called a global mixin.
 
Mixins are a powerful tool, but some caution is needed while using them. As with all injected code, we should be careful to avoid maintenance issues and unexpected behavior.
 
It helps to implement mixins using pure functions that don’t modify anything outside their own scope.
 
Global mixins should be avoided, as affecting every single component can lead to maintenance issues as an application grows. Injecting specific mixins to components as needed leads to more maintainable code.
A single-file component is a file with a .vue extension that contains a Vue component. It contains the component’s template, logic, and styles all bundled together in one file. It consists of one <script> block, optional <template> and <style> blocks, and possible additional custom blocks.
 
To use one, you need to set up Vue Loader for parsing the file (usually done as part of a webpack building pipeline). But this then also supports using non-default languages such as Sass or HTML templating languages with pluggable pre-processors.
The following types of directives are used in Vue.js :
 
* General Directives
* Literal Directives
* Empty Directives
* Custom Directives
You can use event handlers in vue similar to plain javascript. The method calls also support the special $event variable.
<button v-on:click="show('Welcome to VueJS world', $event)">
  Submit
</button>

methods: {
  show: function (message, event) {
    // now we have access to the native event
    if (event) event.preventDefault()
    console.log(message);
  }
}
Normally, javascript provides event.preventDefault() or event.stopPropagation() inside event handlers. You can use methods provided by vue, but these methods are meant for data logic instead of dealing with DOM events. Vue provides below event modifiers for v-on and these modifiers are directive postfixes denoted by a dot.
 
* .stop
* .prevent
* .capture
* .self
* .once
* .passive

Let's take an example of stop modifier,
<!-- the click event's propagation will be stopped -->
<a v-on:click.stop="methodCall"></a>
You can also chain modifiers as below,
<!-- modifiers can be chained -->
<a v-on:click.stop.prevent="doThat"></a>
Vue supports key modifiers on v-on for handling keyboard events. Let's take an example of keyup event with enter keycode.
<!-- only call `vm.show()` when the `keyCode` is 13 -->
<input v-on:keyup.13="show">
Remembering all the key codes is really difficult. It supports the full list of key codes aliases
 
* .enter
* .tab
* .delete (captures both “Delete” and “Backspace” keys)
* .esc
* .space
* .up
* .down
* .left
* .right

Now the above keyup code snippet can be written with aliases as follows,
<input v-on:keyup.enter="submit" />
<!-- OR with shorthand notation -->
<input @keyup.enter="submit" />
You can define custom key modifier aliases via the global config.keyCodes. There are few guidelines for the properties
 
* You can't use camelCase. Instead you can use kebab-case with double quotation marks
* You can define multiple values in an array format
Vue.config.keyCodes = {
  f1: 112,
  "media-play-pause": 179,
  down: [40, 87]
}​
Vue supports below modifiers to trigger mouse or keyboard event listeners when the corresponding key is pressed,
 
* .ctrl
* .alt
* .shift
* .meta

Lets take an example of control modifier with click event,
<!-- Ctrl + Click -->
<div @click.ctrl="doSomething">Do something</div>
In VueJS 2.x, every component must have a single root element when template has more than one element. In this case, you need to wrap the elements with a parent element.
<template>
   <div class="todo-item">
       <h2>{{ title }}</h2>
       <div v-html="content"></div>
   </div>
</template>
Otherwise there will an error throwing, saying that "Component template should contain exactly one root element...".
 
Whereas in 3.x, components now can have multiple root nodes. This way of adding multiple root nodes is called as fragments.
<template>
     <h2>{{ title }}</h2>
     <div v-html="content"></div>
</template>
If you want child wants to communicate back up to the parent, then emit an event from child using $emit object to parent,
Vue.component('todo-item', {
  props: ['todo'],
  template: `
    <div class="todo-item">
      <h3>{{ todo.title }}</h3>
      <button v-on:click="$emit('increment-count', 1)">
        Add
      </button>
      <div v-html="todo.description"></div>
    </div>
  `
})
Now you can use this todo-item in parent component to access the count value.
<ul v-for="todo in todos">
  <li>
    <todo-item
      v-bind:key="todo.id"
      v-bind:todo="todo"
      v-on:increment-count="total += 1"
    /></todo-item>
  </li>
</ul>
<span> Total todos count is {{total}}</span>
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,
 
* Bind the value attribute to a value prop
* 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>
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
  )
})
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  
}  
})  
The three modifiers supported for the v-model directive in Vue.js :
 
lazy : By default, the v-model directive syncs the input with the data after each input event. We can add the lazy modifier to instead sync after change events.
<!-- synced after "change" instead of "input" -->  
<input v-model.lazy="msg" >   

 

number : The number modifier is used to our v-model when we want user input to be automatically typecast as a number. With the type="number", the value of HTML input elements always returns a string. That's why this typecast modifier is required.
<input v-model.number="age" type="number">  ​

 

trim : We should add the trim modifier to our v-model when we want whitespace from user input to be trimmed automatically.
<input v-model.trim="msg">  
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.
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,
 
* 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
  }
}

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

 

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" />
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
      }
    }
  }
})
There are many ways Vue provides transition effects when items are inserted, updated, or removed from the DOM.
 
Below are the possible ways,
 
* Automatically apply classes for CSS transitions and animations
* Integrate 3rd-party CSS animation libraries. For example, Animate.css
* Use JavaScript to directly manipulate the DOM during transition hooks
* Integrate 3rd-party JavaScript animation libraries. For example, Velocity.js
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 }
  ]
})
In Vue.js, the Single File Components are used to solve the common problems in a JavaScript-driven application with a .vue extension.
 
Following is a list of issues solved by Single File Components in Vue.js :
 
* Global definitions specify unique names for every component.
* String templates lack syntax highlighting and require ugly slashes for multiline HTML.
* No CSS support. It means while HTML and JavaScript are modularized into components, CSS is conspicuously left out.
* No, build step restrictions to HTML and ES5 JavaScript, rather than preprocessors like Pug and Babel.
There are two ways to define filters:
 
Local filters : You can define local filters in a component's options. In this case, filter is applicable to that specific component.
filters: {  
  capitalize: function (value) {  
    if (!value) return ''  
    valuevalue = value.toString()  
    return value.charAt(0).toUpperCase() + value.slice(1)  
  }  
} ​
 
Global filters : You can also define a filter globally before creating the Vue instance. In this case, filter is applicable to all the components within the vue instance,
 
Vue.filter('capitalize', function (value) {  
  if (!value) return ''  
  valuevalue = value.toString()  
  return value.charAt(0).toUpperCase() + value.slice(1)  
})  
new Vue({  
  // ...  
})  
In the Vuex application, creating a computed property every time whenever we want to access the store's state property or getter is going to be repetitive, difficult, and boring, especially if a component needs more than one state property. In this situation, we can use the mapState helper of vuex, which generates computed getter functions for us.
 
In the following increment example, we have demonstrated the mapState helper :
// in full builds helpers are exposed as Vuex.mapState  
import { mapState } from 'vuex'  
export default {  
  // ...  
  computed: mapState({  
    // arrow functions can make the code very succinct!  
    username: state => state.username,  
    // passing the string value 'username' is same as `state => state.username`  
    usernameAlias: 'username',  
    // to access local state with `this`, a normal function must be used  
     greeting (state) {  
      return this.localTitle + state.username  
    }  
  })  
}  
You can also pass a string array to mapState when the name of a mapped computed property is the same as a state sub-tree name
computed: mapState([  
  // map this.username to store.state.username  
  'username'  
])
In Vue.js, the $parent property is used to access the parent instance from a child. It is similar to the $root property. The $parent property provides direct access, but it makes the application hard to test and debug. In this property, it is very difficult to find out where the mutation comes from.
In Vue.js applications, memory leaks often come from using third-party libraries that create their own instances and/or manipulate the DOM. The v-if directive and the Vue Router destroy Vue component instances. To overcome this issue, do a cleanup action before the component gets destroyed. It should be done manually in the beforeDestroy() lifecycle hook.
 
For example, suppose we have a fictional library named PowerGraph.js, inside our component. It creates a graph instance that displays some data on the page :
mounted() {  
  this.chart = new PowerGraph();  
}  
Here, we have to call the graph instance's destroy() method or implement our own cleanup method:
beforeDestroy() {  
  this.chart.destroy();  
}  
If we don't do cleanup action before our component gets destroyed, then that memory will never be released, and this will be a memory leak.
Generally, the app is composed of nested components which are nested multiple levels deep. The segments of a URL corresponds to a certain structure of these nested components. To render components into the nested outlet, you need to use the children option in VueRouter constructor config.
 
Let's take a user app composed of profile and posts nested components with respective routes. You can also define a default route configuration when there is no matching nested route.
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User,
      children: [
        {
          // UserProfile will be rendered inside User's <router-view> when /user/:id/profile is matched
          path: 'profile',
          component: UserProfile
        },
        {
          // UserPosts will be rendered inside User's <router-view> when /user/:id/posts is matched
          path: 'posts',
          component: UserPosts
        },
          // UserHome will be rendered inside User's <router-view> when /user/:id is matched
        {  path: '',
           component: UserHome },
      ]
    }
  ]
})
You can chain filters one after the other to perform multiple manipulations on the expression. The generic structure of filter chain would be as below,
{{ message | filterA | filterB | filterB ... }}
In the above chain stack, you can observe that message expression applied with three filters, each separated by a pipe(|) symbol. The first filter(filterA) takes the expression as a single argument and the result of the expression becomes an argument for second filter(filterB) and the chain continue for remaining filters.
 
For example, if you want to transform date expression with a full date format and uppercase then you can apply dateFormat and uppercase filters as below,
{{ birthday | dateFormat | uppercase }}
Sometimes there is a need to extend the functionality of Vue or apply an option to all Vue components available in our application. In this case, mixins can be applied globally to affect all components in Vue. These mixins are called as global mixins.
 
Let's take an example of global mixin,
Vue.mixin({
  created(){
    console.log("Write global mixins")
  }
})

new Vue({
  el: '#app'
})
In the above global mixin, the mixin options spread across all components with the console running during the instance creation. These are useful during test, and debugging or third party libraries. At the same time, You need to use these global mixins sparsely and carefully, because it affects every single Vue instance created, including third party components.
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.
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"
})
VueJS provides proprietary alternatives and plain javascript usage for the template features.
 
Let's list down them in a table for comparision,

Templates Render function
Conditional and looping directives: v-if and v-for Use JavaScript’s if/else and map concepts
Two-way binding: v-model Apply 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 attributes Render functions provide this.$slots and this.$scopedSlots instance properties
Even though VueJS and ReactJS share few common features there are many difference between them :

Feature VueJS ReactJS
Type JavaScript MVC Framework JavaScript Library
Platform Primarily focused on web development Both Web and Native
Learning Curve Easy to learn the framework A steep learning curve and requires deep knowledge
Simplicity Vue is simpler than React React is more complex than Vue
Bootstrap Application Vue-cli CRA (Create React App)
The the syntax of Vue and Angular is common at some points because Angular is the basis for VueJS development in the beginning.

Feature VueJS Angular
Complexity Easy to learn, simple API and design The framework is bit huge and need some learning curve on typescript etc
Binding of Data One-way binding Two-way binding
Learning Curve Easy to learn the framework A steep learning curve and requires deep knowledge
Founders Created by Former Google Employee Powered by Google
Initial Release February 2014 September 2016
Model Based on Virtual DOM(Document Object Model) Based on MVC(Model-View-Controller)
Written in JavaScript TypeScript
React has the following advantages over Vue
 
* ReactJS gives more flexibility in large apps developing
* Easy to test
* Well-suited for mobile apps creation
* The eco system is quite big and well matured.
Vue has the following advantages over React
 
* Vue is smaller and faster
* The convenient templates ease the process of developing
* It has simpler javascript syntax without learning JSX
In large applications, we may need to divide the app into smaller chunks and only load a component from the server when it’s needed. To make this happen, Vue allows you to define your component as a factory function that asynchronously resolves your component definition. These components are known as async component.
 
Let's see an example of async component using webpack code-splitting feature,
Vue.component('async-webpack-example', function (resolve, reject) {
  // Webpack automatically split your built code into bundles which are loaded over Ajax requests.
  require(['./my-async-component'], resolve)
})
Vue will only trigger the factory function when the component needs to be rendered and will cache the result for future re-renders.
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.
In complex applications, vue components will actually be each other’s descendent and ancestor in the render tree.
 
Let's say componentA and componentB included in their respective templates which makes circular dependency,
//ComponentA
<div>
  <component-b >
</div>
//ComponentB
<div>
  <component-a >
</div>
This can be solved by either registering(or wait until) the child component in beforeCreate hook or using webpack's asynchronous import while registering the component,
 
Solution1 :
beforeCreate: function () {
 this.$options.components.componentB = require('./component-b.vue').default
}
Solution2 :
components: {
 componentB: () => import('./component-b.vue')
}
Below are the list of different builds of VueJS based on type of build,
Type UMD CommonJS ES Module (for bundlers) ES Module (for browsers)
Full vue.js vue.common.js vue.esm.js vue.esm.browser.js
Runtime only vue.runtime.js vue.runtime.common.js vue.runtime.esm.js NA
Full (production) vue.min.js NA NA vue.esm.browser.min.js
Runtime-only (production) vue.runtime.min.js NA NA NA
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
    }
  }
}
Vue loader is a loader for webpack that allows you to author Vue components in a format called Single-File Components (SFCs).
 
For example, it authors HelloWorld component in a SFC,
<template>
  <div class="greeting">{{ message }}</div>
</template>

<script>
export default {
  data () {
    return {
      message: 'Hello world for vueloader!'
    }
  }
}
</script>

<style>
.greeting {
  color: blue;
}
</style>
Below are the list of Asset URL transform rules
 
Absolute path : If the URL is an absolute path (for example, /images/loader.png)then it will be preserved as-is.

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.

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.

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.
Scoped CSS is a mechanism in VueJS Single File Components(SFC) that prevents styles from leaking out of the current component and affecting other unintended components on your page. i.e, When a <style> tag has the scoped attribute, its CSS will apply to elements of the current component only. It uses PostCSS to transform scoped css to plain CSS.
 
Let's take an example usage of scoped css,
<style scoped>
.greeting {
  color: green;
}
</style>

<template>
  <div class="greeting">Let's start Scoped CSS</div>
</template>

The above code will be converted to plain CSS,

<style scoped>
 .greeting[data-v-f3f3eg9] {
   color: green;
 }
</style>

<template>
   <div class="greeting" data-v-f3f3eg9>Let's start Scoped CSS</div>
</template>
Below are the steps to use css modules in VueJS,
 
Enable CSS modules : CSS Modules must be enabled by passing modules: true option to css-loader
// webpack.config.js
{
  module: {
    rules: [
      // ... other rules omitted
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          {
            loader: 'css-loader',
            options: {
              // enable CSS Modules
              modules: true,
              // customize generated class names
              localIdentName: '[local]_[hash:base64:8]'
            }
          }
        ]
      }
    ]
  }
}
Add module attribute : Add the module attribute to your <style>
<style module>
.customStyle {
  background: blue;
}
</style>
Inject CSS modules : You can inject CSS modules object with computed property $style
<template>
  <div :class="$style.blue">
    Background color should be in blue
  </p>
</template>
It can work with object/array syntax of :class binding.
You can customize the name of the injected computed property by giving the module attribute a value. This will be helpful to avoid overwriting injected styled if you have more than one <style> tags in a single *.vue component.
 
Example : 
<style module="a">
  /* identifiers injected as a */
</style>

<style module="b">
  /* identifiers injected as b */
</style>
You can perform testing in two ways,
 
Using vue-cli : It offers pre-configured unit testing and e2e testing setups

Manual setup : You can manually setting up unit tests for *.vue files using either mocha-webpack or jest
The store.hotUpdate() API method is used for mutations and modules.
 
For example, you need to configure vuex store as below :
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import myModule from './modules/myModule'

Vue.use(Vuex)

const state = { message: "Welcome to hot reloading" }

const store = new Vuex.Store({
  state,
  mutations,
  modules: {
    moduleA: myModule
  }
})

if (module.hot) {
  // accept actions and mutations as hot modules
  module.hot.accept(['./mutations', './modules/newMyModule'], () => {
    // Get the updated modules
    const newMutations = require('./mutations').default
    const newMyModule = require('./modules/myModule').default
    //swap in the new modules and mutations
    store.hotUpdate({
      mutations: newMutations,
      modules: {
        moduleA: newMyModule
      }
    })
  })
}
A Vuex "store" is basically a container that holds your application state. The store creation is pretty straightforward.
 
Below are the list of instructions to use vuex in an increment application,
 
* Configure vuex in vuejs ecosystem
import Vuex from "vuex";
Vue.use(Vuex)
* Provide an initial state object and some mutations
// Make sure to call Vue.use(Vuex) first if using a module system

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})
* Trigger state change with commit and access state variables,
store.commit('increment')

console.log(store.state.count) // -> 1
Vuex getters acts as computed properties for stores to compute derived state based on store state. Similar to computed properties, a getter's result is cached based on its dependencies, and will only re-evaluate when some of its dependencies have changed.
 
Let's take a todo example which as completedTodos getter to find all completed todos,
const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: 'Vue course', completed: true },
      { id: 2, text: 'Vuex course', completed: false },
      { id: 2, text: 'Vue Router course', completed: true }
    ]
  },
  getters: {
    completedTodos: state => {
      return state.todos.filter(todo => todo.completed)
    }
  }
})
The mapGetters is a helper that simply maps store getters to local computed properties.
 
Example :
import { mapGetters } from 'vuex'

export default {
  computed: {
    // mix the getters into computed with object spread operator
    ...mapGetters([
      'completedTodos',
      'todosCount',
      // ...
    ])
  }
}
You can also commit a mutation is by directly using an object that has a type property.
store.commit({
  type: 'increment',
  value: 20
})

Now the entire object will be passed as the payload to mutation handlers(i.e, without any changes to handler signature).

mutations: {
  increment (state, payload) {
    state.count += payload.value
  }
}
You can share a preset with other developers by publishing it in a git repo. The repo can be published in either github, GitLab or BitBucket. The repo will contain below files,
 
preset.json : The main file containing the preset data and it is required.

generator.js : A generator that can inject or modify files in the project.

prompts.js : A prompts file that can collect options for the generator. You can apply --preset option to use remote presets while creating the project
# use preset from GitHub repo
vue create --preset username/repo my-project
The community plugins and components might need different strategies for different versions. In this case, you can use Vue.version which provides installed version of Vue as a string.
 
Example :
let version = Number(Vue.version.split('.')[0])

if (version === 2) {
  // Vue v2.x.x
} else if (version === 1) {
  // Vue v1.x.x
} else {
  // Unsupported versions of Vue
}
The nextTick method is just a comfortable way to execute a function after the data has been set, and the DOM has been updated. As an example, the usage is going to be similar to setTimeout :
 
// modify data
vm.msg = 'Welcome to Vue'
// DOM not updated yet
Vue.nextTick(function () {
  // DOM updated
})

// usage as a promise (2.1.0+)
Vue.nextTick()
  .then(function () {
    // DOM updated
  })
The loading of all translation files at once is unnecessary and it may impact the performance too. It will be easy for lazy loading or asynchronously loading the translation files when you use webpack. i.e, You can dynamically load or import language translations using webpack as below,
//i18n-setup.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import messages from '@/lang/en'
import axios from 'axios'

Vue.use(VueI18n)

export const i18n = new VueI18n({
  locale: 'en', // set locale
  fallbackLocale: 'en',
  messages // set locale messages
})

const loadedLanguages = ['en'] // our default language that is preloaded

function setI18nLanguage (lang) {
  i18n.locale = lang
  axios.defaults.headers.common['Accept-Language'] = lang
  document.querySelector('html').setAttribute('lang', lang)
  return lang
}

export function loadLanguageAsync (lang) {
  if (i18n.locale !== lang) {
    if (!loadedLanguages.includes(lang)) {
      return import(/* webpackChunkName: "lang-[request]" */ `@/lang/${lang}`).then(msgs => {
        i18n.setLocaleMessage(lang, msgs.default)
        loadedLanguages.push(lang)
        return setI18nLanguage(lang)
      })
    }
    return Promise.resolve(setI18nLanguage(lang))
  }
  return Promise.resolve(lang)
}
After that loadLanguageAsync function can be used inside a vue-router beforeEach hook.
router.beforeEach((to, from, next) => {
  const lang = to.params.lang
  loadLanguageAsync(lang).then(() => next())
})
Vuetify is a semantic component material framework for Vue. It aims to provide clean, semantic and reusable components that make building application easier. The installation and configuration is simple as below,
npm install Vuetify
import Vue from 'vue'
import Vuetify from 'vuetify' // Import Vuetify to your project

Vue.use(Vuetify) // Add Vuetify as a plugin
Advertisement