FrontendDeveloper.in

Vue.js Interview Questions

  • Question 211

    How do you implement Number localization?

    You can localize the number with definition formats(e.g. currency, etc)

    Lets follow below steps to localize numbers,

    1. You need to add definition formats. For example, lets add it for English and Japanese locales
     const numberFormats = {
    'en-US': {
    currency: {
    style: 'currency', currency: 'USD'
    }
    },
    'ja-JP': {
    currency: {
    style: 'currency', currency: 'JPY', currencyDisplay: 'symbol'
    }
    }
    }
    
    1. After that specify the numberFormats option of VueI18n constructor
    const i18n = new VueI18n({
    numberFormats
    })
    
    new Vue({
    i18n
    }).$mount('#app')
    
    1. Now let's configure them in template
    1. Finally it outputs the result
  • Question 212

    How do you perform locale changing?

    All child components of a root instance are localized using the locale property of the VueI18n class. You can change the value of the locale property of the VueI18n instance as below.

    const i18n = new VueI18n({
    locale: 'de', // set locale
    ...
    })
    
    // create root Vue instance
    new Vue({
    i18n,
    ...
    }).$mount('#app')
    
    // change other locale
    i18n.locale = 'en'
    

    You can also use component's VueI18n instance referenced as the $i18n property which will be used to change the locale.

    <template>
    <select v-model="$i18n.locale">
    <option v-for="(lang, i) in langs" :key="`Lang${i}`" :value="lang">{{ lang }}</option>
    </select>
    </template>
    
    <script>
    export default {
    name: 'locale-changer',
    data () {
    return { langs: ['de', 'en'] }
    }
    }
    </script>
    
  • Question 213

    What is Lazy loading translations?

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

    What is vuetify?

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

    How do you watch for nested data changes?

    You can use deep watcher by setting deep: true in the options object. This option enables us to detect nested value changes inside Objects.

    vm.$watch('someObject', callback, {
    deep: true
    })
    vm.someObject.nestedValue = 123
    // callback is fired
    

    Note: This is not required to listen for Array mutations.

  • Question 217

    How to trigger watchers on initialization?

    You can use immediate: true option in order to trigger watchers when the vue instance (or component) is being created. i.e This option will trigger the callback immediately with the current value of the expression.

    watch: {
    test: {
    immediate: true,
    handler(newVal, oldVal) {
    console.log(newVal, oldVal)
    },
    },
    },
    
  • Question 218

    What is the purpose of comments option?

    When comments option enabled, it will preserve and render HTML comments found in templates. By default, it's value is false. Let's see the action in an example,

    <template>
    <!--greeting-->
    <h1>{{ msg }}</h1>
    </template>
    
    <script>
    export default {
    comments: true,
    data () {
    return {
    msg: 'Good morning'
    }
    }
    }
    </script>
    

    Note: This option is only available in the full build, with in-browser compilation. i.e, It won't work with Single File Components(SFC).

  • Question 219

    How to identify whether code is running on client or server?

    You can use vm.$isServer method to know whether the current Vue instance is running on the server or client.

    The usage would be as below,

    const Vue = require('vue');
    Vue.prototype.$isServer
    (OR)
    this.$isServer // With in component
    
  • Question 220

    How do you watch route object changes?

    You can setup a watcher on the $route in your component. It observes for route changes and when changed ,sets the message property.

    watch:{
    $route (to, from){
    this.message = 'Welcome';
    }
    }
    
  • Question 221

    How do you sync current route in vuex store?

    You can use vue-router-sync library to sync current $route object in vuex store's state.

    The usage is quite straight forward with two steps

    1. Installation:
    npm install vuex-router-sync
    
    1. Sync router and store:
    import { sync } from 'vuex-router-sync'
    import store from './vuex/store' // vuex store instance
    import router from './router' // vue-router instance
    
    const unsync = sync(store, router) // Returns an unsync callback function
    unsync() // Unsyncs store from router
    
  • Question 222

    What are navigation guards in vue router?

    The navigation guards of vue-router are used to protect navigations either by redirecting it or canceling it.

    Below are the 3 different ways to hook into router navigations

    1. Global:
    2. Per-route:
    3. In-component:
  • Question 223

    Can I use computed property in another computed property?

    Yes, you can access it directly as you would data props.

    For example, the comboTwo computed property uses comboOne computed property as below,

    data() {
    return {
    propOne: 'prop1',
    propTwo: 'prop2'
    }
    },
    
    computed: {
    comboOne() {
    return this.propOne + ',' + this.propTwo;
    },
    
    comboTwo() {
    return this.comboOne.split(',').join('-');
    }
    }
    
  • Question 224

    How can I use imported constant in template section?

    The variables need to be exposed on your data in order to use them in template section. i.e, You can't use them directly on template.

    <span>
    CREATE: {{CREATE_PROP}}
    UPDATE: {{UPDATE_PROP}}
    DELETE: {{DELETE_PROP}}
    </span>
    <script>
    import {CREATE_DATA, UPDATE_DATA, DELETE_DATA} from 'constants';
    new Vue({
    ...
    data:{
    CREATE_PROP: CREATE_DATA,
    UPDATE_PROP: UPDATE_DATA,
    DELETE_PROP: DELETE_DATA
    }
    ...
    })
    </script>
    
  • Question 225

    Is recommended to use async for computed properties?

    No, it is not recommended. Computed properties should be synchronous. But if you still use asynchronous actions inside them, they may not work as expected and can lead to an unexpected behaviour.

    For example, the below usage of async/await is not recommended,

    async someComputedProperty () {
    return await someFunction()
    },
    

    Note: If you still prefer to use async computed properties for some reason then you can consider using additional plugin such as vue-async-computed.

Get LinkedIn Premium at Rs 399