FrontendDeveloper.in

Vue.js Interview Questions

  • Question 226

    Why the component data must be a function?

    The component data must be a function instead directly providing the object. This is because each instance needs to maintain an independent copy of the returned data object. Otherwise one component instance data changes will impact the data of all other instances.

    For example, the below code snippets gives an idea on correct approach,

    data: { // Bad
    message: 'Hello'
    }
    data: function () { //Good
    return {
    message: 'Hello'
    }
    }
    
  • Question 227

    What is the reason for recommendation for multi-word component names?

    Component names should always be multi-word, except for root level or built-in vue components(such as <transition> or <component> etc). This recommendation is to prevent conflicts with existing and future HTML elements, since all HTML elements are a single word.

    Vue.component('user', { //bad approach
    // ...
    })
    Vue.component('user-profile', { //good approach
    // ...
    })
    
  • Question 228

    What is the best way to re-render a component?

    The best way to force Vue to re-render a component is to set a :key on the component. i.e, Whenever the component to be re-rendered, just change the value of the key then Vue will re-render the component.

  • Question 229

    How does reactivity works with ref?

    VueJS automatically detects the changes to ref's value and updates the DOM with a dependency-tracking based reactivity system.

    1. When a component is rendered for the first time, it tracks every ref that was used during the render.
    2. Whenever a ref is mutated, it will trigger a re-render of the component.
  • Question 230

    How to use composition API in Vue2.0?

    Vue 2.0 does not have native support for the Composition API, but you can use it via the official plugin: @vue/composition-api.

    Let's see the usage in step-by-step instructions,

    1. Install the Plugin
    npm install @vue/composition-api
    # or
    yarn add @vue/composition-api
    
    1. Register the plugin in your main.js file,
    import Vue from 'vue';
    import VueCompositionAPI from '@vue/composition-api';
    
    Vue.use(VueCompositionAPI);
    
    new Vue({
    render: h => h(App),
    }).$mount('#app');
    
    1. Using Composition API in Components You can now use ref, reactive, computed, watch, onMounted, etc., in your Vue 2 components.

    Example: Counter Component

    <template>
    <button @click="increment">Increment</button>
    </template>
    
    <script>
    import { ref } from '@vue/composition-api';
    
    export default {
    setup() {
    const count = ref(0);
    
    const increment = () => {
    count.value++;
    };
    
    return {
    count,
    increment,
    };
    },
    };
    </script>
    

    Note:

    • The @vue/composition-api plugin is compatible with Vue 2.6+.
    • It does not include all Vue 3 features (e.g., <script setup>, Suspense, Fragments).
    • Great for gradual migration or using modern Vue patterns in Vue 2.
  • Question 231

    What is composition API?

    The Composition API in Vue 3 is a new way to organize and reuse logic in Vue components. It was introduced to address some limitations of the Options API (used in Vue 2), especially when dealing with large or complex components where logic can become scattered and hard to manage.

    The Composition API is a set of APIs (e.g., setup(), ref, reactive, computed, watch, etc.) that allow developers to compose component logic more flexibly and cleanly, especially when logic is reused across components.

    Key Concepts
    1. The **setup()** function

    The heart of the Composition API. It's called before the component is created, and it's the place where you declare reactive state, computed properties, methods, and lifecycle hooks.

    <template>
    <button @click="increment">Count is: {{ count }}</button>
    </template>
    <script setup>
    import { ref } from 'vue'
    
    const count = ref(0)
    function increment() {
    count.value++
    }
    </script>
    
    • ref() creates a reactive reference to a primitive value.
    • count.value is how you access/update the value inside a ref.
    1. Reactive State: **ref()** and **reactive()**
    ref()
    • Used for primitive values.
    • Wraps a value in a reactive object.
    const message = ref('Hello');
    message.value = 'Hi';
    
    reactive()
    • Used for objects.
    • Deeply reactive, making every property reactive.
    const user = reactive({  name: 'Alice',  age: 25 });
    user.age++;
    
    1. Computed Properties Creates values that automatically update when dependencies change.
    import { ref, computed } from 'vue';
    
    setup() {
    const firstName = ref('John');
    const lastName = ref('Doe');
    const fullName = computed(() => `${firstName.value} ${lastName.value}`);
    
    return { fullName };
    }
    
    1. Watchers

    Both watch() and watchEffect() are used to run side effects when data changes:

    watch(count, (newVal, oldVal) => {
    console.log('Count changed:', newVal);
    });
    
    watchEffect(() => {
    console.log('Count is now', count.value);
    });
    
    1. Lifecycle Hooks

    Composition API uses new lifecycle hooks imported from Vue.

    import { onMounted, onUnmounted } from 'vue';
    
    onMounted(() => {
    console.log('Component is mounted');
    });
    
    onUnmounted(() => {
    console.log('Component is unmounted');
    });
    
    1. Reusable Logic with Composables

    You can encapsulate logic in composable functions and reuse across components:

    Example: Reuse logic of counter using useCounter.js

    import { ref } from 'vue';
    export function useCounter(initialValue = 0) {
    const count = ref(initialValue);
    const increment = () => count.value++;
    const decrement = () => count.value--;
    const reset = () => count.value = initialValue;
    return { count, increment, decrement, reset };
    }
    

    Using it in a component

    <script setup>
     import { useCounter } from '@/composables/useCounter';
    
    const { count, increment, decrement, reset } = useCounter(5);
    </script>
    
    <template>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
    <button @click="reset">Reset</button>
    </template>
    
  • Question 232

    What are the benefits of composition API?

    The composition API provides several benefits over the traditional Options API as listed below.

    1. Better logic reuse and code organization:
    2. Better typescript support:
    3. Easier testing
    4. Smaller production bundles
  • Question 234

    What is teleport?

    The <Teleport> component allows you to render a part of your component's template into a different location in the DOM — outside the current component's hierarchy.

    Example:

    1. Wrap teleport component around the modal template inside app.vue file
    <template>
    <h1>Page Content</h1>
    
    <!-- This modal will render in the #modals element -->
    <teleport to="#modals">
    </teleport>
    </template>
    
    1. Render modal component inside main index.html file
    <body>
    </body>
    

    In Vue 2, this functionality was possible via the community plugin portal-vue

    Use cases

    1. Modals
    2. Toasts
    3. Tooltips
    4. Context menus
    5. Dropdowns
    6. Anything that needs to break out of DOM nesting
  • Question 235

    What is the purpose of html directive?

    The v-html directive is used to update the inner html of a DOM element with latest data. It is similar to innerHTML property in DOM.

    The example usage of this directive as shown below,

    Note: This directive should be used with trused content only but not on user provided content. Otherwise it can leads to XSS vulnerabilities.

  • Question 236

    What are the key differences between Vue 2 and Vue 3?

    FeatureVue 2Vue 3
    API StyleOptions APIComposition API + Options API
    Reactivity SystemObject.defineProperty()Proxy-based (faster & more reliable)
    PerformanceModerateImproved (~2x faster in some cases)
    Tree-shakingLimitedFully tree-shakable
    TypeScript SupportPartialBuilt-in and first-class support
    Fragment SupportNot supportedSupported
    Teleport/PortalsPlugin-basedNative support
    SuspenseNot availableNative support for async components
  • Question 237

    What is watch() and how is it used?

    The watch() function observes a reactive source((like ref, reactive, getter functions or computed values)) and runs a callback function whenever that source changes.

    Syntax:

    watch(source, callback, options ?)
    
    • source: a ref, reactive property, getter function, or array of them.
    • callback(newValue, oldValue): function to run when the value changes.
    • options (optional): object to control behavior (e.g., immediate, deep).

    Example 1: Watching a ref

    import {ref, watch} from 'vue';
    
    const count = ref(0);
    
    watch(count, (newVal, oldVal) => {
    console.log(`Count changed from ${oldVal} to ${newVal}`);
    });
    count.value = 5; // triggers the watch callback
    

    Example 2: Watching a function (getter)

    const firstName = ref('Sudheer');
    const lastName = ref('Jonna');
    
    watch(
    () => `${firstName.value} ${lastName.value}`,
    (newFullName, oldFullName) => {
    console.log(`Full name changed from ${oldFullName} to ${newFullName}`);
    }
    );
    

    Example 3: Watching a reactive object deeply

    import {reactive, watch} from 'vue';
    
    const user = reactive({name: 'Sudheer', age: 38});
    
    watch(
    () => user,
    (newUser, oldUser) => {
    console.log('User object changed:', newUser);
    },
    {deep: true}
    );
    

    The main uses of watch() are:

    1. Watching route changes
    2. Triggering API calls
    3. Responding to complex data changes
    4. Manually reacting to specific state updates
  • Question 238

    What is watch() and how is it used?

    In Composition API, lifecycle hooks are functions you call inside the setup() function to hook into different stages of a component's lifecycle. These hooks replace the traditional options API lifecycle methods (like created(), mounted(), etc.) with function-based hooks that are imported from Vue.

    Main Lifecycle Hooks

    Lifecycle StageComposition API HookDescription
    Before component creationonBeforeMount()Called right before the component is mounted
    Component mountedonMounted()Called after the component has been mounted
    Before updateonBeforeUpdate()Called before the component updates the DOM
    After updateonUpdated()Called after the component updates the DOM
    Before unmountonBeforeUnmount()Called right before the component is unmounted
    Component unmountedonUnmounted()Called after the component is unmounted
    Error capturedonErrorCaptured()Called when an error from a child component is captured
    Activated (keep-alive)onActivated()Called when a kept-alive component is activated
    Deactivated (keep-alive)onDeactivated()Called when a kept-alive component is deactivated

    The above hooks can be imported from vue and used inside setup() function. For example, the usage of hooks will be as follows,

    import {onMounted, onBeforeUnmount} from 'vue'
    
     export default {
     setup() {
    onMounted(() => {
    console.log('Component is mounted!')
    })
    
    onBeforeUnmount(() => {
    console.log('Component is about to unmount')
    })
     }
     }
    
  • Question 239

    Whats the difference between `watch()` and `watchEffect()`?

    Both watch and watchEffect are Composition API functions used for reactivity, but they serve different purposes and behave differently.

    watch: It is used to watch specific reactive sources (like ref or computed) and respond to changes. This function is lazy. i.e, The callback is not called immediately but only on changes. It is useful when you need to access both old and new values, and performs side-effects conditionally.

    watch(count, (newVal, oldVal) => {
    console.log('Count changed:', newVal);
    });
    

    watchEffect: This function is automatic and eager. It runs a function immediately and tracks its dependencies automatically. It cannot access old values directly.

    watchEffect(() => {
    console.log(`Count is ${count.value}`);
    });
    
Get LinkedIn Premium at Rs 399