All topics

Vue interview questions

20 questions with answers. 183 open jobs in India ask for Vue.

  1. What does the @ mean inside an import path?

    This is done with Webpack resolve.alias configuration option and isn't specific to Vue.

    In Vue Webpack template, Webpack is configured to replace @/ with src path:

      const path = require('path');
      ...
      resolve: {
        extensions: ['.js', '.vue', '.json'],
        alias: {
          ...
          '@': path.resolve('src'),
        }
      },
      ...
    

    The alias is used as:

    import '@/<path inside src folder>';
    

    From Stack Overflow: asked by Chris Schmitz, answered by Estus Flask (CC BY-SA 4.0)

  2. Can you force Vue.js to reload/re-render?

    Try this magic spell:

    vm.$forceUpdate();
    //or in file components
    this.$forceUpdate();
    

    No need to create any hanging vars :)

    Update: I found this solution when I only started working with VueJS. However further exploration proved this approach as a crutch. As far as I recall, in a while I got rid of it simply putting all the properties that failed to refresh automatically (mostly nested ones) into computed properties.

    More info here: https://v2.vuejs.org/v2/guide/computed.html

    From Stack Overflow: asked by Dave, answered by Boris Mossounov (CC BY-SA 4.0)

  3. Difference between v-model and v-bind on Vue.js?

    From here - Remember:

    <input v-model="something">
    

    is essentially the same as:

    <input
        v-bind:value="something"
        v-on:input="something = $event.target.value"
    >
    

    or (shorthand syntax):

    <input
        :value="something"
        @input="something = $event.target.value"
    >
    

    So v-model is a two-way binding for form inputs. It combines v-bind, which brings a js value into the markup and v-on:input to update the js value. The js value must be present in your data, or in an inject.

    Use v-model when you can. Use v-bind/v-on when you must :-) I hope your answer was accepted.

    v-model works with all the basic HTML input types (text, textarea, number, radio, checkbox, select). You can use v-model with input type=date if your model stores dates as ISO strings (yyyy-mm-dd). If you want to use date objects in your model (a good idea as soon as you're going to manipulate or format them), do this.

    v-model has some extra smarts that it's good to be aware of. If you're using an IME ( lots of mobile keyboards, or Chinese/Japanese/Korean ), v-model will not update until a word is complete (a space is entered or the user leaves the field). v-input will fire much more frequently.

    v-model also has modifiers .lazy, .trim, .number, covered in the doc.

    From Stack Overflow: asked by Gustavo Dias, answered by bbsimonbb (CC BY-SA 4.0)

  4. Can I pass parameters in computed properties in Vue.Js

    Most probably you want to use a method

    <span>{{ fullName('Hi') }}</span>
    methods: {
      fullName(salut) {
          return `${salut} ${this.firstName} ${this.lastName}`
      }
    }
    

    Longer explanation

    Technically you can use a computed property with a parameter like this:

    computed: {
       fullName() {
          return salut => `${salut} ${this.firstName} ${this.lastName}`
       }
    }
    

    (Thanks Unirgy for the base code for this.)

    The difference between a computed property and a method is that computed properties are cached and change only when their dependencies change. A method will evaluate every time it's called.

    If you need parameters, there are usually no benefits of using a computed property function over a method in such a case. Though it allows you to have a parametrized getter function bound to the Vue instance, you lose caching so not really any gain there, in fact, you may break reactivity (AFAIU). You can read more about this in Vue documentation https://v2.vuejs.org/v2/guide/computed.html#Computed-Caching-vs-Methods

    The only useful situation is when you have to use a getter and need to have it parametrized. For instance, this situation happens in Vuex. In Vuex it's the only way to synchronously get parametrized result from the store (actions are async). Thus this approach is listed by official Vuex documentation for its getters https://vuex.vuejs.org/guide/getters.html#method-style-access

    From Stack Overflow: asked by Saurabh, answered by damienix (CC BY-SA 4.0)

  5. Difference between the created and mounted events in Vue.js

    created() : since the processing of the options is finished you have access to reactive data properties and change them if you want. At this stage DOM has not been mounted or added yet. So you cannot do any DOM manipulation here

    mounted(): called after the DOM has been mounted or rendered. Here you have access to the DOM elements and DOM manipulation can be performed for example get the innerHTML:

    console.log(element.innerHTML)
    

    So your questions:

    1. Is there any case where created would be used over mounted?

    Created is generally used for fetching data from backend API and setting it to data properties. But in SSR mounted() hook is not present you need to perform tasks like fetching data in created hook only

    1. What can I use the created event for, in real-life (real-code) situation?

    For fetching any initial required data to be rendered(like JSON) from external API and assigning it to any reactive data properties

    data:{
        myJson : null,
        errors: null
    },
    created(){
        //pseudo code
        database.get().then((res) => {
            this.myJson = res.data;
        }).catch((err) => {
            this.errors = err;
        });
    }
    

    From Stack Overflow: asked by lesssugar, answered by Vamsi Krishna (CC BY-SA 4.0)

  6. Methods vs Computed in Vue

    Computed values and methods are very different in Vue and are definitely not interchangeable in most cases.

    Computed Property

    A more appropriate name for a computed value is a computed property. In fact, when the Vue is instantiated, computed properties are converted into a property of the Vue with a getter and sometimes a setter. Basically you can think of a computed value as a derived value that will be automatically updated whenever one of the underlying values used to calculate it is updated. You don't call a computed and it doesn't accept any parameters. You reference a computed property just like you would a data property. Here's the classic example from the documentation:

    computed: {
      // a computed getter
      reversedMessage: function () {
        // `this` points to the vm instance
        return this.message.split('').reverse().join('')
      }
    }
    

    Which is referenced in the DOM like this:

    <p>Computed reversed message: "{{ reversedMessage }}"</p>
    

    Computed values are very valuable for manipulating data that exists on your Vue. Whenever you want to filter or transform your data, typically you will use a computed value for that purpose.

    data:{
        names: ["Bob", "Billy", "Mary", "Jane"]
    },
    computed:{
        startsWithB(){
            return this.names.filter(n => n.startsWith("B"))
        }
    }
    <p v-for="name in startsWithB">{{name}}</p>
    

    Computed values are also cached to avoid repetitively calculating a value that doesn't need to be re-calculated when it hasn't changed (as it might not be in a loop for example).

    Method

    A method is just a function bound to the Vue instance. It will only be evaluated when you explicitly call it. Like all javascript functions, it accepts parameters and will be re-evaluated every time it's called. Methods are useful in the same situations any function is useful.

    data:{
        names: ["Bob", "Billy", "Mary", "Jane"]
    },
    computed:{
        startsWithB(){
            return this.startsWithChar("B")
        },
        startsWithM(){
            return this.startsWithChar("M")
        }
    },
    methods:{
        startsWithChar(whichChar){
            return this.names.filter(n => n.startsWith(whichChar))
        }
    }
    

    Vue's documentation is really good and easily accessible. I recommend it.

    From Stack Overflow: asked by Bootstrap4, answered by Bert (CC BY-SA 4.0)

  7. `ref()` vs `reactive()` in Vue 3?

    Key Points

    • reactive() only takes objects, NOT JS primitives (String, Boolean, Number, BigInt, Symbol, null, undefined)
    • ref() is calling reactive() behind the scenes
    • Since reactive() works for objects and ref() calls reactive(), objects work for both
    • BUT, ref() has a .value property for reassigning, reactive() does not have this and therefore CANNOT be reassigned

    Use

    ref() when..

    • it's a primitive (for example 'string', true, 23, etc)
    • it's an object you need to later reassign (like an array - more info here)

    reactive() when..

    • it's an object you don't need to reassign, and you want to avoid the overhead of ref()

    In Summary

    ref() seems like the way to go since it supports all object types and allows reassigning with .value. ref() is a good place to start, but as you get used to the API, know that reactive() has less overhead, and you may find it better meets your needs.

    ref() Use-Case

    You'll always use ref() for primitives, but ref() is good for objects that need to be reassigned, like an array.

    setup() {
        const blogPosts = ref([]);
        return { blogPosts };
    }
    getBlogPosts() {
        this.blogPosts.value = await fetchBlogPosts();
    }
    

    The above with reactive() would require reassigning a property instead of the whole object.

    setup() {
        const blog = reactive({ posts: [] });
        return { blog };
    }
    getBlogPosts() {
        this.blog.posts = await fetchBlogPosts();
    }
    

    reactive() Use-Case

    A good use-case for reactive() is a group of primitives that belong together:

    const person = reactive({
      name: 'Albert',
      age: 30,
      isNinja: true,
    });
    

    the code above feels more logical than

    const name = ref('Albert');
    const age = ref(30);
    const isNinja = ref(true);
    

    Useful Links

    If you're still lost, this simple guide helped me: https://www.danvega.dev/blog/2020/02/12/vue3-ref-vs-reactive/

    An argument for only ever using ref(): https://dev.to/ycmjason/thought-on-vue-3-composition-api-reactive-considered-harmful-j8c

    The decision-making behind why reactive() and ref() exist as they do and other great information, the Vue Composition API RFC: https://vuejs.org/guide/extras/composition-api-faq.html#why-composition-api

    From Stack Overflow: asked by Denis Tsoi, answered by Chris Hayes (CC BY-SA 4.0)

  8. Vuex Action vs Mutations

    Question 1: Why did the Vuejs developers decide to do it this way?

    Answer:

    1. When your application becomes large, and when there are multiple developers working on this project, you will find that "state management" (especially the "global state") becomes increasingly more complicated.
    2. The Vuex way (just like Redux in react.js) offers a new mechanism to manage state, keep state, and "save and trackable" (that means every action which modifies state can be tracked by debug tool:vue-devtools)

    Question 2: What's the difference between "action" and "mutation"?

    Let's see the official explanation first:

    Mutations:

    Vuex mutations are essentially events: each mutation has a name and a handler.

    import Vuex from 'vuex'
    const store = new Vuex.Store({
      state: {
        count: 1
      },
      mutations: {
        INCREMENT (state) {
          // mutate state
          state.count++
        }
      }
    })
    

    Actions: Actions are just functions that dispatch mutations.

    // the simplest action
    function increment ({commit}) {
      commit('INCREMENT')
    }
    // a action with additional arguments
    // with ES2015 argument destructuring
    function incrementBy ({ dispatch }, amount) {
      dispatch('INCREMENT', amount)
    }
    

    Here is my explanation of the above:

    • A mutation is the only way to modify state
    • The mutation doesn't care about business logic, it just cares about "state"
    • An action is business logic
    • The action can commit more than 1 mutation at a time, it just implements the business logic, it doesn't care about data changing (which is managed by mutation)

    From Stack Overflow: asked by Kobi, answered by Kaicui (CC BY-SA 4.0)

  9. What is the difference between the views and components folders in a Vue project?

    First of all, both folders, src/components and src/views, contain Vue components.

    The key difference is that some Vue components act as Views for routing.

    When dealing with routing in Vue, usually with Vue Router, routes are defined in order to switch the current view used in the <router-view> component. These routes are typically located at src/router/routes.js, where we can see something like this:

    import Home from '@/views/Home.vue'
    import About from '@/views/About.vue'
    export default [
      {
        path: '/',
        name: 'home',
        component: Home,
      },
      {
        path: '/about',
        name: 'about',
        component: About,
      },
    ]
    

    The components located under src/components are less likely to be used in a route whereas components located under src/views will be used by at least one route.

    Vue CLI aims to be the standard tooling baseline for the Vue ecosystem. It ensures the various build tools work smoothly together with sensible defaults so you can focus on writing your app instead of spending days wrangling with configurations. At the same time, it still offers the flexibility to tweak the config of each tool without the need for ejecting.

    Vue CLI aims for rapid Vue.js development, it keeps things simple and offers flexibility. Its goal is to enable teams of varying skill levels to set up a new project and get started.

    At the end of the day, it is a matter of convenience and application structure.

    • Some people like to have their Views folder under src/router like this enterprise boilerplate.
    • Some people call it Pages instead of Views.
    • Some people have all their components under the same folder.

    Choose the application structure that best suits the project you are working on.

    From Stack Overflow: asked by drsnark, answered by Ricky Ruiz (CC BY-SA 4.0)

  10. Is there a way to dispatch actions between two namespaced vuex modules?

    You just need to specify that you're dispatching from the root context:

    // from the gameboard.js vuex module
    dispatch('notification/triggerSelfDismissingNotifcation', {...}, {root:true})
    

    Now when the dispatch reaches the root it will have the correct namespace path to the notifications module (relative to the root instance).

    This is assuming you're setting namespaced: true on your Vuex store module.

    From Stack Overflow: asked by Chris Schmitz, answered by Jake (CC BY-SA 4.0)

  11. Difference between @click and v-on:click Vuejs

    There is no difference between the two, one is just a shorthand for the second.

    The v- prefix serves as a visual cue for identifying Vue-specific attributes in your templates. This is useful when you are using Vue.js to apply dynamic behavior to some existing markup, but can feel verbose for some frequently used directives. At the same time, the need for the v- prefix becomes less important when you are building an SPA where Vue.js manages every template.

    <!-- full syntax -->
    <a v-on:click="doSomething"></a>
    <!-- shorthand -->
    <a @click="doSomething"></a>
    

    Source: official documentation.

    From Stack Overflow: asked by LorenzoBerti, answered by FitzFish (CC BY-SA 4.0)

  12. What is nextTick and what does it do in Vue.js?

    It's all about Timing

    nextTick allows you to execute code after you have changed some data and Vue.js has updated the virtual DOM based on your data change, but before the browser has rendered that change on the page.

    Normally, devs use the native JavaScript function setTimeout to achieve similar behavior, but using setTimeout relinquishes control over to the browser before it gives control back to you (via calling your callback).

    Example

    Let's say you changed some data; Vue then updates the vDOM based on that data change (the changes are not yet rendered to the screen by the browser).

    If you used nextTick at this point, your callback would get called immediately, and the browser would update the page after that callback finished executing.

    If you instead used setTimeout, then the browser would have a chance to update the page, and then your callback would get called.

    You can visualize this behavior by creating a small component like the following:
    (Check this fiddle to see it live)

    <template>
      <div class="hello">
        {{ msg }}
      </div>
    </template>
    <script>
    export default {
      name: 'HelloWorld',
      data() {
        return {
            msg: 'One'
        }
      },
      mounted() {
          this.msg = 'Two';
          this.$nextTick(() => {
              this.msg = 'Three';
          });
      }
    }
    </script>
    

    Run your local server. You will see the message "Three" being displayed.

    Now, replace this.$nextTick with setTimeout:

    setTimeout(() => {
        this.msg = 'Three';
    }, 0);
    

    Reload the browser. You will see "Two" before you see "Three".

    That's because, with setTimeout:

    1. Vue updated the vDOM to say "Two"
    2. Vue gave control to the browser
    3. The browser displayed "Two"
    4. Callback was called
    5. Vue updated the vDOM to say "Three"
    6. Vue gave control to the browser
    7. The browser displayed "Three"

    But with nextTick, we skip steps 2 and 3! Instead of passing over control after the first vDOM update, Vue calls the callback immediately, which prevents the browser from updating until the callback is finished. In this example, that means "Two" is never actually displayed.

    To understand how Vue implements this, you need to understand the concept of the JavaScript Event Loop and microtasks.

    Once you have those concepts clear(er), check the source code for nextTick.

    From Stack Overflow: asked by hidar, answered by Prashant (CC BY-SA 4.0)

  13. Vue 'export default' vs 'new Vue'

    When you declare:

    new Vue({
        el: '#app',
        data () {
          return {}
        }
    )}
    

    That is typically your root Vue instance that the rest of the application descends from. This hangs off the root element declared in an html document, for example:

    <html>
      ...
      <body>
        <div id="app"></div>
      </body>
    </html>
    

    The other syntax is declaring a component which can be registered and reused later. For example, if you create a single file component like:

    // my-component.js
    export default {
        name: 'my-component',
        data () {
          return {}
        }
    }
    

    You can later import this and use it like:

    // another-component.js
    <template>
      <my-component></my-component>
    </template>
    <script>
      import myComponent from 'my-component'
      export default {
        components: {
          myComponent
        }
        data () {
          return {}
        }
        ...
      }
    </script>
    

    Also, be sure to declare your data properties as functions, otherwise they are not going to be reactive.

    From Stack Overflow: asked by rockzombie2, answered by user320487 (CC BY-SA 4.0)

  14. Can vue-router open a link in a new tab?

    I think that you can do something like this:

    const routeData = this.$router.resolve({name: 'routeName', query: {data: "someData"}});
    window.open(routeData.href, '_blank');
    

    It worked for me.

    Update

    For composition Api:

    import { useRouter } from 'vue-router'
    const router = useRouter();
    const routeData = router.resolve({name: 'routeName', query: {data: "someData"}});
    window.open(routeData.href, '_blank');
    

    From Stack Overflow: asked by Tang Jiong, answered by Rafael A. Cespedes Basteiro (CC BY-SA 4.0)

  15. Do we have router.reload in vue-router?

    this.$router.go() does exactly this; if no arguments are specified, the router navigates to current location, refreshing the page.

    note: current implementation of router and its history components don't mark the param as optional, but IMVHO it's either a bug or an omission on Evan You's part, since the spec explicitly allows it. I've filed an issue report about it. If you're really concerned with current TS annotations, just use the equivalent this.$router.go(0)

    As to 'why is it so': go internally passes its arguments to window.history.go, so its equal to windows.history.go() - which, in turn, reloads the page, as per MDN doc.

    note: since this executes a "soft" reload on regular desktop (non-portable) Firefox, a bunch of strange quirks may appear if you use it but in fact you require a true reload; using the window.location.reload(true); (https://developer.mozilla.org/en-US/docs/Web/API/Location/reload) mentioned by OP instead may help - it certainly did solve my problems on FF.

    From Stack Overflow: asked by Saurabh, answered by user719662 (CC BY-SA 4.0)

  16. What is the difference between "vite" and "vite preview"?

    npm run dev (or vite) starts a local web server with Hot Module Replacement for development, and will automatically change when code changes

    npm run build (or vite build) builds the project, and outputs to the folder ./dist

    npm run preview (or vite preview) start a local web server that serves the built solution from ./dist for previewing

    Beware

    • You need to run build before preview.

    • Preview will always preview the latest build, and will not update automatically when code changes.

    From Stack Overflow: asked by user3848207, answered by tauzN (CC BY-SA 4.0)

  17. Vue.js - How to properly watch for nested data

    You can use a deep watcher for that:

    watch: {
      item: {
         handler(val){
           // do stuff
         },
         deep: true
      }
    }
    

    This will now detect any changes to the objects in the item array and additions to the array itself (when used with Vue.set). Here's a JSFiddle: http://jsfiddle.net/je2rw3rs/

    EDIT

    If you don't want to watch for every change on the top level object, and just want a less awkward syntax for watching nested objects directly, you can simply watch a computed instead:

    var vm = new Vue({
      el: '#app',
      computed: {
        foo() {
          return this.item.foo;
        }
      },
      watch: {
        foo() {
          console.log('Foo Changed!');
        }
      },
      data: {
        item: {
          foo: 'foo'
        }
      }
    })
    

    Here's the JSFiddle: http://jsfiddle.net/oa07r5fw/

    From Stack Overflow: asked by Plastic, answered by craig_h (CC BY-SA 4.0)

  18. How can I get query parameters from a URL in Vue.js?

    According to the docs of route object, you have access to a $route object from your components, which exposes what you need. In this case

    // from your component
    console.log(this.$route.query.test) // outputs 'yay'
    

    From Stack Overflow: asked by Rob, answered by Yerko Palma (CC BY-SA 4.0)

  19. How to listen for 'props' changes?

    You can watch props to execute some code upon props changes:

    new Vue({
      el: '#app',
      data: {
        text: 'Hello'
      },
      components: {
        'child' : {
          template: `<p>{{ myprop }}</p>`,
          props: ['myprop'],
          watch: { 
            myprop: function(newVal, oldVal) { // watch it
              console.log('Prop changed: ', newVal, ' | was: ', oldVal)
            }
          }
        }
      }
    });
    <script src="https://unpkg.com/vue@2/dist/vue.min.js"></script>
    <div id="app">
      <child :myprop="text"></child>
      <button @click="text = 'Another text'">Change text</button>
    </div>

    From Stack Overflow: asked by Amio.io, answered by Egor Stambakio (CC BY-SA 4.0)

  20. Disable input conditionally (Vue.js)

    To remove the disabled prop, you should set its value to false. This needs to be the boolean value for false, not the string 'false'.

    So, if the value for validated is either a 1 or a 0, then conditionally set the disabled prop based off that value. E.g.:

    <input type="text" :disabled="validated == 1">
    

    Here is an example.

    var app = new Vue({
      el: '#app',
      data: {
        disabled: 0
      }
    }); 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <button @click="disabled = (disabled + 1) % 2">Toggle Enable</button>
      <input type="text" :disabled="disabled == 1">
        
      <pre>{{ $data }}</pre>
    </div>

    From Stack Overflow: asked by Zaffar Saffee, answered by asemahle (CC BY-SA 4.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.