Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

<script>  export default {    data() {      return {        author: {          name: 'John Doe',          books: [            'Vue 2 - Advanced Guide',            'Vue 3 - Basic Guide',            'Vue 4 - The Mystery'          ]        }      }    },    computed: {      publishedBooksMessage() {        return this.author.books.length > 0 ? 'Yes' : 'No'      }    }  }  </script>    <template>    <p>Has published books:</p>    <span>{{ publishedBooksMessage }}</span>  </template> 

Answer»

The state is an important part of Vue applications SINCE it is concerned with how data is passed among components. 

  • State management - is putting all the shared states of components in one place so that there will only be a single source of truth. This helps in achieving consistency of the state between all components making use of it. Generally, state management is all about accessing, centralizing, and saving the state of the whole application in a structured and organized way rather than passing it from one to another component. There are state management libraries like vuex or one can create his own STORE and make it a single source of truth where every component using the state has access to the properties as well as the actions. 
  • Prop drilling - props are used to pass data from PARENT to child. The use of props is EFFECTIVE until deep chaining of components is encountered. This is when a distant component in a large component tree and a deeply nested component want something from a distant ancestor component. In this case, all of the intermediate components should have to pass props from the distant ancestor across the entire CHAIN

State management is better: 

  • As there is no passing of pross along the entire chain for the distant component to use the data. 
  • Since it is easier to maintain, less prone to bugs, and easier to work with. 
2.

Second: 

Answer»
  • Stateful logic -  involves managing the state which changes over time. It is concerned with data that is of a different state whose state is changing EVERY time. 

Example: tracking the position of some moving object, as the time passes if something is in motion then its position is changing. so, we can say the position has a different state and a logic performing some manipulation on position is called stateful logic. 

  • Stateless logic - takes a certain input value and just RETURNS the expected result. It deals with stateless data whose value is not changing over time. We are not considering the PREVIOUS value of the data but the current one only. There are many libraries that are used in every programming language, for example date formatting. This library, WHATEVER value you passed to it, will give you a date format that is always the same. 

Generally stateless logic does not involve a RECORD of previous interactions and each and every interaction request has to be handled based on information that is new (that comes with the request). 

3.

<script>  export default {    data() {      return {        author: {          name: 'John Doe',          books: [            'Vue 2 - Advanced Guide',            'Vue 3 - Basic Guide',            'Vue 4 - The Mystery'          ]        }      }    },    methods: {      publishedBooksMessage() {        return this.author.books.length > 0 ? 'Yes' : 'No'      }    }  }  </script>  <template>    <p>Has published books:</p>    <span>{{ publishedBooksMessage() }}</span>  </template> 

Answer»

//FancyButton template  <template>    <button class="fancy-btn">    <slot/>  </button>  </template>    <style>  .fancy-btn {    border-radius: 8px;  }  </style>  //Parent template  <script>  import FancyButton from './FancyButton.vue'      export default {    components: { FancyButton}  }  </script>    <template>    <FancyButton>      <span> CLICK me! </span>    </FancyButton>  </template> 

>> Output 

he slot has similar usage with PROPS as it is down-way passing but it is used to pass a template fragment to a child component, and let the child component render the fragment it received within its own template rather than passing data. So, in the above code ‘<slot/>’ represents the content (template fragment) to be passed by the parent. Therefore, the  ‘click me!’ text is what is to be replaced by the slot tag. 

As for changing the color of the text from the parent FALLTHROUGH ATTRIBUTE is used. Here the attribute is the style and the value of the attribute will be ’red’ assignment to the color attribute as shown below.

<FancyButton>      <span style="color:red">Click me! </span>    </FancyButton> 

>> Output 

4.

First: 

Answer»
  • Fallthrough attributes are v-on event listeners or attributes which are passed to other components implicitly. This means it does not involve the explicit DECLARATION of the attribute or event in the receiving component’s props (from parent to child) or emit (from child to parent). 
  • Props is an option in the parent component to list what PROPERTIES of the child are to be ACCESSED by the parent. So, it is down-way referencing unlike emit. In the parent component properties to be accessed are listed so that the child component can use those properties as an attribute name and assign a value when referencing the child instance. 
  • Emit is used to emit custom events in template expressions directly. They are used in up-way binding from parent to child so that the parent performs some modification on the value passed to it by the child component. ‘$emit’ specifies the event name and optional value to be passed to the event which will be accessed by the parent component where some logic will be performed on it. 

What MAKES the fallthrough attributes unique is - 

  • We do not have to explicitly specify what is to be inherited in the inheriting component rather the attribute or the event passed will apply to the component without specifying its declaration in its own component 

Example 

<!-- template of <Button1> -->  <BUTTON>click here</button>  <Button1 class="large" /> //included in another component  <!-- final render of template of <Button1> after fallthrough attribute -->  <button class="large">click here</button>
5.

The following two codes have the same output which is ‘yes’. Which one is more preferable performance-wise and why? 

Answer»

The Parent component 

<script>  import Child from './Child.VUE'    export default {    components: {      Child    },    MOUNTED() {      this.$refs.child  }  }  </script>    <template>    <Child ref="child" />  </template> 

The Child component 

export default {    EXPOSE: ['dataTwo', 'methodOne'],    data() {      return {        dataOne: 'foo',        dataTwo: 'bar'      }    },    methods: {      MethodOne() {        /* ... */      },      MethodTwo() {        /* ... */      }    }  } 

The two properties that are FULLY accessible to the parent are 'dataTwo', 'methodOne' (those which are listed in the expose option). Since the other two properties of the child (‘dataOne’, ‘methodTwo’) are not included in the expose option, they will not be accessible to the parent component which is referencing the child. ref is one of Vue’s special attributes which allows us to obtain a specific DOM object’s direct reference or the instance of the child component after it is mounted. In our case, it references the instance of the child component which allows the parent component to access all of its properties unless the expose option is used in the child component. 

The parent component would have full access to all properties of the child if the expose option was not used since ‘ref’ ATTRIBUTE is referencing the instance of the child component. Therefore the expose option is what limits the other properties from being accessed by the parent component. 

6.

Explain the dissimilarity between one-way data flow and two-way data binding? Which vue.js directive is used for each?

Answer»

The second one is preferable performance-wise since it uses the computed property. 

Computed property : 

  • saves us from putting too much logic in our templates which might MAKE them HARD to maintain 
  • is cached based on reactive dependency. If there is no CHANGE in the value of reactive data the previously cached value is used RATHER than recomputing the result which increases performance.  
  • allows us to reuse a logic if it is needed more than once in the template rather than repeating the logic everywhere 
  • is recommended for COMPLEX logic that includes reactive data 
  • Method invocation always evaluates the logic whether the reactive data changes or not rather than caching the result like a computed property. 
7.

Why should arrow functions not be used in writing lifecycle hooks in Vue instances?

Answer»
  1. One-way data flow implies that the model is the only source of TRUTH. In CONTRAST, two-way data-BINDING means that UI fields are found to model data. Therefore, in case of the UI field changes, the model data also changes and vice-versa. 
  2. One-way data flows are deterministic; in contrast, the two-way binding is associated with SEVERAL side effects that are difficult to identify and understand. 
  3. In the one-way data flow, the UI part of the application does not update automatically when a data model is changed. We ought to write some custom code to update every time a data model changes. V-bind is UTILIZED for one-way data flow or binding. For two-way data binding, the UI part of the application automatically revises when the data Model is changed. The V-model directive is utilized for two-way data binding. 
8.

Explain Vue.js common issues when tracking changes?

Answer»

The most common lifecycle hooks are mounted, UPDATED, and unmounted. All lifecycle hooks are called with their ‘this’ context pointing to the current active INSTANCE invoking it. 

Arrow functions are not independent, and as a result, they cannot DEFINE a ‘this’ of their own. But arrow functions are bound to their parent’s function’s context. 

The Arrow function (=>), when used in the Vue app, the Arrow function (=>), the keyword ‘this’ does not bind to the Vue instance, resulting in errors. 

HENCE it is advised to use the standard function declaration instead of the arrow function, as shown below. 

export default {  mounted() {  console.log(`the component is now mounted.`) } }
9.

const router = new VueRouter({         routes: [           { path: '/user/:name', component: User }            { path: '/user/:name', component: Admin }           { path: '/user/:name', component: Customer }         ]       }) 

Answer»

All properties defined in Vue instances are reactive. It means that the components are automatically updated and re-rendered in case of changes at any instance. 

All these properties will change to getters and setters in the initialization stage.  

Following setbacks should be considered while designing a Vue app; 

JavaScript LIMITATIONS: Vue cannot detect the deletion or addition of an object property. Vue performs the getter/setter CONVERSION process during instance initialization; property must be PRESENT in the data object for Vue to convert it and make it reactive.  

Example: 

VAR vm = new Vue({    data: {   a: 1   }  })  // `vm.a` is now reactive  vm.b = 2  // `vm.b` is NOT reactive 

Additionally, it cannot detect the modification of array items. Vue does not ALLOW adding new root-level reactive properties to a created instance.  

It is feasible to add reactive properties to a nested object using the Vue.set(object, propertyName, value) method, as shown below. 

Vue.set(vm.someObject, 'b', 2)
10.

Does the following code have any errors? If yes, what is the error and how are you supposed to correct it? If not, which component (User,Admin,Customer) is going to be invoked when ‘/user/:name’ is navigated to.

Answer»

No, the code does not have any error, but SOMETIMES the URL might be matched by multiple routes, and the CONFUSION of which path needs to be MAPPED can be resolved by route matching priority. The priority is based on the ORDER of route configuration. i.e., The route which is declared first has higher priority. 

  • In our case, the URL (/user/:name) is assigned multiple COMPONENTS (User, Admin, and Customer) to be routed, which creates confusion. 
  • Since route matching priority is based on the order in which the routes were defined, the first component,' User,' will be invoked, and the other two ways are left unconsidered. 
11.

What is the data flow heeded by props, and what are the possible solutions for mutation cases?

Answer»

All props follow a ONE-way-down binding between the child's property and the PARENT one. i.e., when the parent property is updated, that latest prop value will be passed down to the child, but not the other way(child to parent, which is carried out by emitting events rather than using props).  

The child component should not mutate the prop defined in the parent; otherwise, it throws a warning in the console. The possible mutation cases can be solved in the ways illustrated below.  

The possible mutation cases are: 

  1. When you try to use parent prop as the initial value for child property: 

The solution for this mutation case is defining a local property in the child component and assigning the parent value as the initial value. The following code snippet clarifies the solution. 

props: ['defaultUser'], 
  • defaultUser prop is the one defined in the parent component whose value is GOING to be assigned to the child's local property as an initial value. 

data: function () {    return {     username: this.defaultUser    }  }
  • Username is the local property of the child whose initial value is the parent's prop (defaultUser) 

  1. When you try to transform the parent prop: 

The solution for this mutation case is defining a computed property using the prop's value. Computed properties are ANOTHER powerful feature from Vue that allows us to transform or perform calculations on our data and easily REUSE the result as an up-to-date variable in our template. 

Below is the illustration of computed properties to mutate the parent's prop  

 props: ['environment'],  computed: {   localEnvironment: function () {     return this.environment.trim().toUpperCase()    }  }
12.

What are Components in Vue.js? Show how to create one inside a Vue instance.

Answer»

In Vue.js component 

  • ONE of the essential features of VueJS is that it creates custom ELEMENTS
  • It is a reusable Vue instance with a name that can be reused as many times as we want. 

Steps to create a Vue component called ‘ComponentOne’ INSIDE the Vue instance. 

Step 1: Create the component by defining a COMMON element of the UI(User interface) to be displayed. Save the file with name ComponentFirst.vue 

<template&GT;  <div><h1>This is coming from component First</h1></div>  </template> 

The component consists of an h1 tag nested in div tag to print ‘This is coming from component First’ at the size of heading one. 

Step 2: Define the vue instance in which the component is imported (included) 

<script>  import ComponentOne from './ComponentFirst.vue'  export default {    components: {      ComponentFirst  }  </script>    <template>  < h1 >Here is the reused component!</h1>  <ComponentFirst />  <ComponentFirst />  </template> 

>> Output 

  • Here is the reused component! 
  • This is coming from component First 
  • This is coming from component First 
13.

What will the output of the following code be and why?

Answer»

<script>  export default {    data() {      return {        someObject: {}      }    },  methods:{  print(){   const newObject = {}      this.someObject = newObject      console.log(newObject === this.someObject)}  },    mounted() {     this.print();    }  }    </script> 

>> Output 

False. 

The Vue JavaScript framework is "reactive," which can automatically refresh your data. Reactivity is when changes in the application state are automatically reflected in the DOM (DOCUMENT Object Model), a programming API for HTML and XML documents.  

In this case, we have a Proxy object (in our case someObject) that ENABLES us to create a proxy for another object (in our case newObject), which can intercept and redefine fundamental operations for that object.  

When this.someObject object is accessed, the value is a reactive proxy of the original newObject. The original newObject is left unchanged and will not be made reactive. 

The use of Proxy does introduce a new CAUTION to be aware of: the proxied object(someObject) is not equal to the original object(newObject) in terms of identity comparison (===).That is why the actual output is false rather than true, EVEN if the value assigned to each object is the same.

14.

Based on the code below, when would the value for ‘answer’ instance compute either yes or no? Which Vue.js feature is used for initiating the action?

Answer»

<script>  export default {    data() {      return {        question: '',        answer: 'Questions mostly contain question mark'      }    },    watch: {      question(newQuestion, oldQuestion) {        if (newQuestion.indexOf('?') > -1) {          this.getAnswer()        }      }    },    methods: {      async getAnswer() {        this.answer = 'Thinking...'        try {          const res = await fetch('https://yesno.wtf/api')          this.answer = (await res.json()).answer        } catch (e) {          this.answer = 'Error! Could not reach the API. ' + error        }      }    }  }  </script>    <template>    <p>      Ask a yes/no question:      <input v-model="question" />    </p>    <p>{{ answer }}</p>  </template> 

  • The computation of the 'answer' instance to either 'yes' or 'no' will be triggered when the question's value changes to a new one and the question mark is included in the question. Otherwise, the 'answer' value will remain as 'Questions usually contain a question mark.' 
  • Vue.js feature triggers the action 'watch,' a unique feature that allows one to watch a COMPONENT and perform defined ACTIONS when the component's value changes.  

Defining watch, the FUNCTION that prevents the modification in the state should have the same NAME as the reactive instance. In this case, it is observed that the function name has two parameters (newQuestion, oldQuestion) . If the function's name DIFFERS from the reactive instance, nothing will happen to the value of the 'answer' even if the question is modified and the question mark is included. 

15.

Explain what are detection mutation methods and array detection non-mutation methods? List three array detection mutation methods and two array detection non-mutation methods with their uses?

Answer»

Mutation methods ALTER the original array.  

Following are the list of array mutation methods that initiate VIEW updates 

  • push() - is used to ADD an element to the end of an array 
  • pop() - is used to remove the last element of an array 
  • shift() - is used to remove the first element of an array. 
  • unshift() - adds an element at the beginning of an array. 
  • splice() - is used for various purposes 
    • insert an element at the specified index 
    • replace one or multiple elements in an array 
    • remove an element from the selected index 
  • sort() - is used to sort an array in ascending ORDER 
  • reverse() - is used to reverse an array 

Below are the methods that don't mutate the original array but return a new array and are CALLED non-mutation methods.  

  • filter() - Used to filter array within the given condition 
  • contact() - To combine two arrays and add elements to the last array element 
  • slice() - Returns a copy of a portion of an array 
16.

What do we use to pass data from child component to parent component and how (specify the steps required)?

Answer»

Values go up from child to parent using the $EMIT() event. 

Step 01: Invoke the $emit() method in the child to send a piece of the data to its parent component. 

//ChildComponent.vue  <template>   <button @click="$emit('name', 'RAJESH Bhagia')">click me</button>  </template> 

The first statement in the $emit method is the event name, and the second ARGUMENT is the actual data to be passed to the parent component. 

Step 02: Use the same event name prefixed with the @ symbol to define the child component inside the template in the parent component. 

Its VALUE will be a function, and it will have the actual value RETURNED in its argument. 

STEP 03: Declare the getName function inside the methods objects with an argument 

 

//ParentComponent.vue  <script>  import ChildComponent from './ChildComponent.vue'      export default {    components: {      ChildComponent    },    methods:{    getName(value) {//Step 03        console.log(value);     }  }  }  </script>    <template>  <h3>Below is the child component within the parent component!</h3>  <ChildComponent @name="getName"/> //STEP 02  </template> 

The value passed to the getName function is the one assigned on the ChildComponent which is “Rajesh Bhagia”.So it is the one which is passed to the parent component by emitting an event. 

>> Output after button click in child component 

>> Rajesh Bhagia
17.

What is the mounted event in Vue.js?

Answer»
  • mounted EVENT: Among the list of LIFE cycle hooks.  It is called after the DOM has been mounted or rendered. DOM elements are accessed, and DOM MANIPULATION can be performed, for example, get the innerHTML 

console.log(element.innerHTML) 
  • When a Vue instance is created in Vue.js, there are various steps to be followed. Initially, they are created then mounted, and finally destroyed at the END. WITHIN this process, life cycle hooks are run. Life cycle hooks allow us to add code of their interest at specific stages. 
  • Life cycle hooks mounted events are the most used ones. Developers have full access to reactive data, templates, and rendered DOM. 
18.

What are local filters?

Answer»
  • A FILTER is a simple function in JavaScript that is used to modify the output of DATA to the BROWSER. Filters do not change the data directly WHEREVER it is stored rather, it applies certain formatting to our data. There would not be any change in the data but the output of the data to a browser is CHANGED
  • Local filters - are defined in the component’s options. Here, the filter applies to that specific component that defined the filter only, not to any other component in the application. 
19.

What is two-way data binding? Which directive is used for the two-way data binding?

Answer»
  • Two-way data-binding means that UI (User Interface) fields are found to model data. Therefore, in the CASE of the UI field changes, the model data also changes and vice-versa so both are the source of truth. The two-way binding is associated with several side effects that are difficult to identify and UNDERSTAND
  • In two-way data binding, the view (UI) PART of the application updates automatically when the data model is modified. In Vue.js the directive v-model is used for two-way data binding. 
  • Generally, in the two-way data binding, the UI part of the application usually updates automatically when the data model is changed. 
  • V-model - is a directive for two way data binding. It automates the updating of input by picking the correct way. 
<input v-model="message" PLACEHOLDER="edit me">  <p>Message is: {{ message }}</p>   

When the VALUE in the input field changes ‘message’ in the p tag automatically updates. 

20.

What is the v-show directive? Show with a simple example code.

Answer»
  • V-show - it is SIMILAR to the v-if directive as it is CONCERNED with showing or hiding DOM elements but it renders all elements to the DOM and uses show/hide CSS properties to show or hide elements in the DOM. It is used when we need frequent switching between on and off for a DOM element. 

<h1 v-show="ok">Hello!</h1> 

An element with a v-show which is ‘h1’ will always be rendered and remain in the DOM; v-show only toggles the display CSS property of the element. 

Example for V-show 

<div id="app">  <div v-show="showText">  <p>Show the first nice text</p>  </div>  <div v-show="!showText">  <p>Show the second bad text</p>  </div>  <button v-on:CLICK="showText = !showText">Toggle texts</button>  </div>  NEW Vue({  el: "#app",  data: {  showText: TRUE,  }  }) 

Result: 

  • This is the first nice text 
  • IF the ShowText is false 
  • This is the Second bad text 
21.

What are the drawbacks of mixins?

Answer»

Mixin is a Vue.js feature that allows code reusability between components in Vue.js application instances and a software composition tool. 

The drawback of MIXINS

  • As mixins are powerful tools, there are some issues to be taken care of while using them. UNEXPECTED behavior, as well as maintenance issues, should be considered as well with all codes included in the components. 
  • Global mixins (that are APPLIED to every component), should be avoided since modifying every single component would most of the time LEAD to maintenance issues as an application grows. Adding specific mixins to certain components as needed helps in writing a more MAINTAINABLE code. 
22.

Which lifecycle hook plays a great role for memory leak not to occur?

Answer»

A memory leak occurs when memory is allocated for use and not deallocated where the memory area is no longer needed. It is caused by a PROGRAM that does not deallocate (free up) the extra memory allocated and FREQUENT memory leaks might halt everything. 

  • In VUE.js, memory leak does not usually come from Vue itself, rather other third-party libraries CAUSE a memory leak by manipulating the DOM or by creating their instances. 
  • For memory leaks not to occur, we have to manually clean up any third-party instances in the beforeDestroy() lifecycle hook. 

Example:  

mounted() {    this.chart = new PowerGraph();  } 

When the component is mounted the third-party library is created so it has to be destroyed in the beforeDestroy() lifecycle hook for memory leak not to occur as shown below. 

beforeDestroy() {    this.chart.destroy();  } 

If the clean-up is not done before our component gets destroyed, then that memory is never going to be RELEASED. Hence, a memory leak occurs. 

23.

What do we mean by stateless logic? Give an example.

Answer»
  • STATELESS logic - takes a CERTAIN INPUT value and just returns the expected result. It deals with stateless data whose value is not CHANGING over time. We are not considering the previous value of the data but the current one only.  
  • Many libraries are used in every programming language, for example, the date formatting library. This library, whatever value you passed to it, will give you a date format that is always the same. 

GENERALLY stateless logic does not involve a record of previous interactions and every interaction request has to be handled based on new information (that comes with the request). 

24.

What is a one-way data flow?

Answer»
  • One-way data FLOW means that the model is the only way we can change the value of data so it is the only source of truth. 
  • One-way data flows are deterministic, UNLIKE the two-way binding which is associated with several side effects that are difficult to identify and understand. 
  • In the one-way data flow, the view (UI) part of the application does not update automatically when the value of the data model is modified. Some custom code is needed to make it updated EVERY time a data model is changed. In Vue.js the DIRECTIVE v-bind is used for one-way data flow or binding. 
  • Generally, for one-way data flow, the UI aspect of the application cannot update automatically. This, in turn, RESULTS in a need to customize certain codes to help it update every time there is a change in the data model. 
25.

Explain what reactivity is in Vue.js.

Answer»
  • The Vue JavaScript framework is "reactive", which means it can automatically refresh your DATA. Reactivity is the phenomenon in which changes in the application state are automatically reflected in the DOM (Document Object Model) which is a programming API for HTML and XML documents. It defines the logical structure, the WAY a document is accessed and MANIPULATED
  • Reactivity is a programming paradigm that allows us to adjust to changes in a declarative manner.  
  • All properties DEFINED in Vue INSTANCES are mostly reactive. This means in case of any change to the properties; the components automatically update and re-render. 
  • Therefore, all these properties are changed to getters and setters in the initialization stage giving Vue the ability to detect these properties when they are changed. 
26.

The splice() method has several uses. Specify what type of array detection method it is and list at least two from its usage.

Answer»
  • splice() - is one of the array DETECTION mutation methods that mutate or change the original array. Mutation methods do not INVOLVE creating of new array they just perform some modifications to the original array 
  • splice() – has VARIOUS uses as LISTED below: 
    • to add an element at the SPECIFIED index 
    • to replace elements in the array (can be one or multiple elements) 
    •  to remove an element in the selected index 
27.

What causes prop drilling in Vue.js?

Answer»
  • Prop drilling - props are used to pass data from parent to CHILD. The use of props is effective until deep chaining of components is encountered.  
  • Prop drilling is caused when a distant component in a LARGE component tree and a deeply nested component want something from a distant ancestor component. In this case, all of the intermediate components should have to pass props from the distant ancestor across the entire chain. 
  • It involves the PASSING of props ALONG the entire chain for the distant component to use the data. 
  • It is difficult to maintain, PRONE to bugs, and is hard to work. 
28.

What is the name of a logic which involves managing the state which changes over time? Give an example.

Answer»
  • Stateful logic -  involves managing the state which changes over time. It is concerned with data that is of a different state whose state is changing every time. Stateless logic involves a record of previous interactions and every INTERACTION request has to be handled based on information not only from the request but the previous ONE also. 

Example: TRACKING the position of some moving object, as the time passes if something is in motion then its position is changing. So we can say the position has a different state and a logic performing MANIPULATION on the position is called stateful logic. 

// eventBus.jsimport Vue from 'vue'export const bus = new Vue()// component_one.vueimport { bus } from './eventBus.js'export default {    data() {        RETURN {            value: null        }    }    methodcreated() {// Listens for the 'action' eventbus.$on('action', ({ payload }) => {            this.value = payload        })}}// component_two.vueimport {bus} from './eventBus.js'export default {created() {// Emits the 'action' eventbus.$emit('action', {myPayload: 45678})}}
29.

What are the uses of computed properties in Vue.js?

Answer»

A computed property is  one of the powerful features from Vue that enables US to transform our data by performing calculations on the VALUE of the data and then easily REUSING the result as an up-to-date variable in our template.

Computed properties have the FOLLOWING usage: 

  • saves us from putting too much logic in our templates which might make them hard to maintain 
  • Computed properties are cached based on reactive dependency. If there is no CHANGE in the value of reactive data the previously cached value is used rather than recomputing the result which increases performance.  
  • allows us to reuse a logic if it is needed more than once in the template rather than repeating the logic everywhere 
  • is recommended for complex logic that includes reactive data 
30.

What are fallthrough attributes in Vue.js?

Answer»

Fallthrough attributes are v-on event listeners or attributes which are passed to other components implicitly. This means it does not involve the EXPLICIT declaration of the attribute or event in the receiving component’s props (from parent to child) or emit (from child to parent). 

We do not have to EXPLICITLY specify what is to be inherited in the inheriting component rather the attribute or the event passed will apply to the component without specifying its declaration in its component 

EXAMPLE 

<!-- TEMPLATE of <Button1> -->  <button>click here</button>  <Button1 CLASS="large" /> //included in another component  <!-- final render of template of <Button1> after fallthrough attribute -->  <button class="large">click here</button>
31.

What is the use of the push() method on the array?

Answer»
  • push() is one of the array detection mutation METHODS that mutate or change the ORIGINAL array. It alters or updates the original array by adding an element to its end. 
  • Since it is a mutation method there is no need to CREATE a new array rather the original array itself is modified by adding an element to the end of its original elements. 
arrayName.push({ attributeName: 'value' })
32.

What are Vue.js Watchers? In which case do we use them?

Answer»
  • Watchers - are Vue.js FEATURES that are USED for the triggering of the action ‘watch’ which is a special feature that allows one to watch a component and perform specified actions when the value of the component changes. It is a more generic WAY to observe and react to data changes in the Vue instance. 
  • Computed properties also allow us to compute derived values. But, in cases where there is a need to perform side effects in response to change in the state the computed property is not sufficient. THEREFORE, we use watchers in this case to perform side effects. 
  • Watchers are used for triggering action with a function WHENEVER a reactive property changes. 
33.

What is state management in Vue.js and which library is commonly used in Vue for state management?

Answer»

The state is an important part of Vue applications since it is concerned with how data is passed among components. 

  • State MANAGEMENT - is putting all the shared states of components in one place so that there will only be a single source of truth. This helps in achieving consistency of the state between all components making use of it.  
  • Generally, state management is all about accessing, centralizing, and saving the state of the whole application in a STRUCTURED and organized way rather than passing it from one to another COMPONENT.  
  • The commonly used state management library in Vue is vuex but we can also CREATE our STORE and make it a single source of truth where every component using the state has access to the properties as well as the actions. 
34.

How do we create a Vue.js instance? Write the code.

Answer»

In VUE.js application must always start with the creation of a new instance which is created USING the Vue function as shown below. 

// code for CREATING vm Vue.js instance  var vm = new Vue(  {     // OPTIONS  }  ) 

Options indicate a PLACE where we include different options to be included in the Vue instance when it is first created.

35.

What are props in Vue.js?

Answer»

Props - is an option in the parent component to list what properties of the child are to be accessed by the parent. So, it is down-WAY referencing unlike emit which is used in up-way binding from parent to child so that the parent performs some modification on the value passed to it by the child component. 

In the parent component properties to be passed are listed so that the child component can use those properties as an attribute name and assign a value when referencing the child instance. Vue props allow a parent component to pass DATA to a child component. Props are used for passing data down the component tree; to pass data up the component tree (from child to parent), you can use $emit() or Vuex 

Create a component in Vue and pass a description object. The description.props field specifies what props the component can receive. The easiest way is to list your props as an array of property names.  

In the below example, the GREET component takes in a single prop, name. It then uses the name prop in its template. 

Vue.component('greet', {    props: ['name'],    template: `      <DIV>        Hello, {{name}}      </div>    `  });    CONST app = new Vue({    template: `<greet name="Universe!"></greet>`  }); 

The name prop is passed to greet as a static prop in the above example in the Vue app. In other words, 'Universe' is a hard coded string. To pass  dynamic prop (a prop bound to a variable), prefix the name with v-bind: when creating the component: 

Vue.component('greet', {    props: ['name'],    // Renders "Hello, Universe"    template: `      <div>        Hello, {{name}}      </div>    `  });    const app = new Vue({    data: () => ({ value: 'Universe' }),    // Note the `v-bind:` prefix. If you forget it, `greet` will treat    // 'value' as a raw string and render "Hello, value"    template: `<greet v-bind:name="value"></greet>`  }); 

All props follow a one-way binding which is a down-way binding between the child's 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 other way (child to the parent which is carried out by emitting events rather than using props).  

36.

What are the differences and similarities between v-if and v-show directives?

Answer»
  • V-if - it is a directive that is USED to REMOVE or add DOM elements based on the given CONDITION it specifies as a condition. 
  • V-show - it is similar to the v-if directive as it is concerned with showing or hiding of DOM element but it RENDERS all elements to the DOM and uses show/hide CSS properties to show or hide elements in the DOM. It is used when we need frequent switching between on and off for a DOM element. 

Their similarity is that both are involved in adding or removing DOM elements. What makes them different is v-if uses conditions while v-show uses CSS properties to determine WHETHER to add an element or not. 

37.

Declarative-rendering is a common phenomenon in Vue.js and other frameworks. What is it and how is it achieved in Vue.js?

Answer»

In the past JavaScript used domineering methods to INFLUENCE DOM but over time, it has become outdated. Declarative rendering has taken precedence in recent times. Declarative rendering allows data to decide how the DOM is RENDERED. With Vue.js we are able to input and let the framework TAKE precedence and display the output correctly. When rendering data in Vue.js, we use curly braces as place holders to insert data into the DOM. With the above capability, Vue.js ability has been elevated to power deep sophisticated single page applications with the help of few modern TOOLS. It has a powerful enough library to EXECUTE and hold complex operations. 

Below is an example of a declarative instance: 

Const parent = new Vue ({           el : ‘#parent’,            data : {    name : ‘ Vue.js’  }  }) 

The above programme outputs a message “ Welcome to the exciting world of Vue.js 

38.

Ensuring that the defined CSS styles in single files are applied singularly to a component is a vital skill for a Vue.js developer. How would you achieve this if applied to one component only?

Answer»

Modern applications USING CSS files tend to grow with TIME to levels that certain styles cannot be EASILY traced. This makes it DIFFICULT to even initiate a change or an update on the styles. Although single file components has allowed DEVELOPERS to grow in writing more logical ways compared to writing them in several languages, tracking certain styles in huge applications is quite difficult. Thanks to scoped styles, such challenges have been curbed. Scoped styles allow us to put down CSS that only apply to the components we need.  

An example of applied scoped styles is shown below.  <style scoped>  .example {         Color: red;  }  </style>    <template>        <div class=”example”>hi</div>  </template> 

In this example, the example class will only apply to that particular component only. This is accomplished by putting another data attribute to serve all the other elements within that particular component that are still engulfed by the initial CSS. Doing this does not prevent the styles from being influenced by other exterior styles, only that scoped styles are selfish. They do not allow leakage of their styles to other components. There are many other Vue styles such as deep styles, slotted styles, global styles, style modules among many other styles. They perform different but closely related functions to the scoped styles. 

39.

More often developers tend to use the letters “vm”. They use it as a variable name to declare the root Vue application instance. What do the letters refer to for this case?

Answer»

Finding an easier way of performing tasks is one of the major functions of developers. Finding ways of DECLARING instances in a more simple way has led to the use of the two letters ‘vm’ to declare variable instances. Every vue instance begins by creating a completely fresh Vue instance. This uses the vue function.  

Var vm = new Vue ( {  }) 

Above is an illustration of how instance declaration is done in Vue. To some extent, we can say that Vue instance declaration was inspired by the Model-View-View-Model (MVVM) pattern. vm SHORT form for ViewModel has earned the status of conventional instance declaration in vue. Many vue applications have root Vue instances embedded with new Vue are organized into NESTED trees with reusable mechanisms.

Naming an instance as vm is not compulsory, ALTHOUGH many developers use it this way. As long as a compiler is able to compile successfully with minimal ERRORS and produce an output on the template, any naming can be used so long as it is easy and simple to understand.   

40.

Vue.js has several lifecycle hooks. What is your understanding of lifecycle hooks as used in vue.js?

Answer»

Vue instances undergo a lot of process from the moment they are initialized to the point where they are wrecked and exterminated. Lifecycle in vue is the compilation of activities right from data set up and observation to compiling the template, to mounting of the methods in the Direct Object Method (DOM), to bringing up-to-date the DOM as a result of data change. While those activities are taking place inside the DOM, some functions are naturally performed in them. Those functions are what are called lifecycle hooks. 

The diagrammatic representation below illustrates the various processes of the vue lifecycle. 

Vue has eight major lifecycle hooks. They are; created, before created, mounted, before mounted, updated, before updated, destroyed and before destroyed. All these lifecycle hooks play a VITAL ROLE in vue.js framework. Before creation is the first lifecycle that gets called immediately an instance is initialized. It is visualized as shown below:  

<template>,   <div>  < h1 >Vue Lifecycle hooks</h1>  <ul>  <li v-for="(item, n) in LIST" :key="n">  {{ item }} <a @click="deleteItem(item)">Delete</a>  </li>  </ul>  <strong  >Add a new item in the list array and save while running localhost to  preview the destroy hooks</strong>  </div>  </template>  <script>  export default {  data() {  return {  list: [  'Apex Legends',  'A Plague Tale: Innocence',  'ART SQOOL',  'Baba Is You',  'Devil May Cry 5',  'The Division 2',  'Hypnospace Outlaw',  'Katana ZERO',  ],  }  },  methods: {  deleteItem(VALUE) {  this.list = this.list.filter(item => item !== value)  },  },  beforeCreate() {  alert('beforeCreate: data is static, thats it')  },  created() {  alert('created: data and events ready, but no DOM')  },  beforeMount() {  alert('beforeMount: $el not ready')  },  mounted() {  alert('mounted: DOM ready to use')  },  beforeUpdate() {  alert(  'beforeUpdate: we know an update is about to happen, and have the data'  )  },  updated() {  alert('updated: virtual DOM will update after you click OK')  },  beforeDestroy() {  alert('beforeDestroy: about to blow up this component')  },  destroyed() {  alert('destroyed: this component has been destroyed')  },  }  </script>  <style lang="scss" scoped>  ul {  padding-left: 0;  }  li {  display: block;  list-style: none;  + li {  margin-top: 10px;  }  }  a {  display: inline-block;  BACKGROUND: rgb(235, 50, 50);  padding: 5px 10px;  border-radius: 10px;  font-size: 10px;  color: white;  text-transform: uppercase;  text-decoration: none;  }  </style>  The lifecycle hooks are called in a sequence beginning with the “before” then followed by the original.  An example of a running program is as below  new Vue({  data: {  b: 1  },  created: function () {          // ‘this’ points to the vm instance          console.log( ba is: ’ + this.b)     }  })  // => “b is: 1”
41.

Passing of data from a primary component to a secondary component is a common feature for Vue.js and Angular.js. How would you achieve data pass from parent to child component in Vue.js?

Answer»

Just like in the real world, parents are viewed as a source of knowledge or better less more experience. A child seeks more information from a parent and the parent either teaches or writes down steps and procedures to be followed. In the development world and as in our case, Vue.js FRAMEWORK, DATA is passed to a child component through attributes or as attributes. Data can be passed inline or using the component method. Methods are the reusable vue requests that separate the code and the modular. Its incorporation has helped to reduce REPETITIONS. Props are the most commonly used passage. They are one way inlets in the component. 

<Script&GT;  Export default {     Name: ‘child’,      Props: {          parentData: Object,          stringProp: String,          title: String     }  }  </script> 

In the above example, the prop is declared in the child section for it to appear as a normal variable.  

42.

How would you describe computed properties in Vue.js?

Answer»

Vue.js provides an amazing platform for achieving dynamism or static values to be visual on the template. The use of DIRECT hardcoding into the HTML, text outburst or MODEST expressions to transform the data has been a way for achieving the basics. Complex computations have necessitated the development of computed properties.  

Computed property declaratively describes how one value solely depends on other values. Computed properties have revolutionized complex expressions in that we can create properties which can alter, manipulate, transform and present information in a more readable, efficient and UNDERSTANDABLE manner. Computed properties use methods in its library which is a huge plus. Methods are ALWAYS recomputed when ACCESSED unlike computed property which does not recompute thus providing accurate outputs. Computed properties can be used in so many ways. Data filtering, calculations, execution of Boolean conditions are just a few of the applications of computed properties. Below is a basic example of a computed property that uses count: 

    <div>  </template>    <script>  Export default {    name: “HelloWorld”,    data() {         return{             ShopNumber: 2      }  },   Computed: {        Count: function()  {              Return ‘The shop number is ‘ + this.shopNumber           }      }  };  </script>  <div> 

From the above count property, this.shopNumber is the dependency data and it returns a sentence that has this.shopnumber that is displayed in the template. 

43.

What is the directive in Vue.js?

Answer»

Directive is a PIECE of instruction to perform a certain task. In vue.js a directive is a sign that that directs the LIBRARY to perform an action to the DOM. Directives in Vue.js are much simpler to understand compared to in Angular.js. Directives in vue.js are in HTML prefix format. Some of the directives INCLUDE; V-show, v-if, v-on, v-for, v-bind and v-model.

They appear in the following format;

<element Prefix-directiveId=”[argument:] expression [| filters…]”> </element>

Directives give permission to the template to act according to the changes in accordance to the defined logic by use of methods, data PROPERTIES and inline expressions. An example of a directive is below.

<SignUpButton V-On:click= “doSignup” />

Here, a v-on directive is used to implement a click on the component. The message is to perform or allow the user to sign up. Apart from the above-mentioned directives, vue.js allows us to define our own directives based on what we need to perform. V directives are easier to understand and implement in the development world. Developers are prioritizing it although prior knowledge in Angular or any other structure is an added advantage. Prior knowledge provides a baseline for understanding how Document Object Model works and how directives manipulate it.

44.

While juggling through the world of development using vue.js, you are required to use a two-way data binding between the data attribute and an input box. How would you implement this?

Answer»

Two-way data binding refers to data sharing between components class and the template. Two way binding is a powerful tool for developing JavaScript patterns. For instance when one side is changed, the other also CHANGES to match the other. When a value is altered or changed in the input box, the value of the component class also changes. The best way to implement two-way data binding is by the use of v-model. V-model is essential as it allows updating of data. V-model assumes VUE instance as the primary source of data and thus it ignores initial checked, selected or value attributes.  

The initial VALUES only need to be declared in the JavaScript. For instance:

<input type=”text” :value=”nameInput” @keyup= “nameInput = $EVENT.target.value”> 

The data attribute ‘nameInput’ is assigned the input box when there is an event in ‘keyup’. This way, we are binding the input box to the data attribute and that is how two-way binding is achieved. There is a firm RELATIONSHIP flanked by the form field and information property. Compared to manual setup, v-model handles the process quicker and more efficiently.

45.

As a developer, you notice that developing a Single Page Application (SPA) requires routing. How would you achieve/use routing?

Answer»

One of the unique features of vue.js is routing in Single Page Applications. The vue router allows the transition from one page to another page on the user interface without NECESSARILY the need for request from the server. Routing in Single Page Applications is achieved through the use of vue-router library. The collection offers a variety of feature sets such as the personalized/customized scroll behavior, transitions, nested routes, HTML5 history MODE and route structures and wildcards. Vue router also allows integration of some third party routers. In vue applications, vue router is the library that allows navigation on the APP. An example of achieved routing is in vue app. In the application, it is easier to move from one page to another thanks to the vue router. Most of the modern single page applications use the vue router. To build a simple page component without using the full features of router library, simple routing is required as in the example below:

const NotFound = { template: '<p>Page not found</p>' } const Home = { template: '<p>home page</p>' } const About = { template: '<p>about page</p>' } const routes = {   '/': Home,   '/about': About } new Vue({   el: '#app',   data: {   currentRoute: window.location.pathname   },   COMPUTED: {     ViewComponent () {       return routes[this.currentRoute] || NotFound     }   },   render (h) { return h(this.ViewComponent) } })
46.

Vue.js is commonly referred to as a ‘progressive framework’. What is your typical understanding of progressive framework in vue.js?

Answer»

Vue.js is not only a progressive framework, it is known by developers as the progressive framework. Vue.js has earned its progressive framework term due to its unique characteristics. Although it is simple and flexible, it has various powerful features which attract many developers. It is still fresh in the development world, easy to maneuver and fairly direct. Vue.js permits the development of any desired application structure which frameworks such as Angular.js and React.js do not OFFER. Also, vue.js is an open-source framework. This particularly means a lot in the development environment. It is highly versatile and lightweight in nature. It is the view which allows the DISPLAY of data packets in single-page applications. Those few mentioned QUALITIES among many others have earned vue.js its ‘progressive nature’ badge. Vue.js is a user-friendly framework. It is the best choice for beginners due to its ease of use. For the experienced developers, vue.js library provides a view layer. One can PICK it and integrate with any other framework. As an HTML developer, the use of vue.js makes you realize how its learning curve is quite forgiving. It is FAIR to say vue.js was created as a simple version of all the other complex frameworks.