Google News
logo
Vue.JS Interview Questions
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