Accreditation Bodies
Accreditation Bodies
Accreditation Bodies
Supercharge your career with our Multi-Cloud Engineer Bootcamp
KNOW MOREVue.js is a progressive JavaScript framework used for building user interfaces. It is highly adaptable and can be integrated into projects of various sizes. Whether you’re appearing for a beginner or advanced-level interview our set of Vue.js interview questions will help you prepare for it. The questions are divided into different sections, such as SPA, odes, lifecycle hooks, and directives. With Vue.js interview questions, you can be confident that you will be well-prepared for your next interview. If you are seeking to progress your career in Vue.js, this guide is an ideal reference for you.
Filter By
Clear all
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.
Expect to come across this popular question in Vue.js technical interview questions.
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, the 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 the 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) } })
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.
It's no surprise that this one pops up often in Vue.js interview questions.
Directive is a piece of instruction to perform a certain task. In vue.js a directive is a sign that directs the library to perform an action to the DOM. Directives in Vue.js are much simpler to understand compared to 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.
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.
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> 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.
A common interview question on Vue.js, don't miss this one.
Vue instances undergo a lot of processes from the moment they are initialized to the point where they are wrecked and exterminated. Lifecycle in Vue is the compilation of activities from data setup and observation to compiling the template, to mounting 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”
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.
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.
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
One of the most frequently posed interview questions is Vue.js, be ready for it.
Their similarity is that both are involved in adding or removing DOM elements. What makes them different is that v-if uses conditions while v-show uses CSS properties to determine whether to add an element or not.
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).
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.
The state is an important part of Vue applications since it is concerned with how data is passed among components.
arrayName.push({ attributeName: 'value' })
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>
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:
A staple in Vue.js developer interview questions, be prepared to answer this one.
Example: tracking the position of some moving object; as 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})}}
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).
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.
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.
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:
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:
<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.
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)
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
Mutation methods alter the original array.
Following are the list of array mutation methods that initiate view updates
Below are the methods that don't mutate the original array but return a new array and are called non-mutation methods.
<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>
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.
A common question in Vue.js advanced interview questions, don't miss this one. <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.
In Vue.js component
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> <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
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:
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)
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() } }
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.
One of the most frequently posed Vue.js interview questions for experienced, be ready for it.
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)
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.`) } }
The second one is preferable performance-wise since it uses the computed property.
Computed property :
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.
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>
//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
A staple in Vue.js interview questions and answers, be prepared to answer this one.
Stateful logic - involves managing the state, which changes over time. It is concerned with data of a different state whose state changes every time.
Example: tracking the position of some moving object. As time passes, if something is in motion, then its position changes. so, we can say the position has a different state and logic performing some manipulation on the 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 pass 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).
The state is an important part of Vue applications since it is concerned with how data is passed among components.
State management is better:
const MockComponent = { props: { showMe: { type: Boolean, }, }, template: ` <div v-if="showMe"> This is a test component </div> `, }; new Vue({ el: '#app', components: { MockComponent, }, template: ` <div> <MockComponent showMe="" /> </div> `, });
>> Output
If a boolean prop exists in the child whether a value is assigned to it or not then its value will be evaluated to true. In the above code, we can see that ‘showMe’ which is a boolean prop has an assigned value which is an empty string so the value of the ‘showMe’ will be true. And there will not be any error in the output.
If ‘<MockComponent />’ was replaced by ‘ <MockComponent showMe="" />’ in the above code then since ‘showMe’ does not exist, the value of the boolean prop would have been false. Therefore, there would not have been anything printed on the screen.
Memory leak 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 own instances.
In order for memory leaks not to occur, we have to manually clean up any third-party instances in beforeDestroy() lifecycle hook.
Example:
mounted() { this.chart = new PowerGraph(); }
When the component is mounted, a third-party library is created so it has to be destroyed in beforeDestroy() lifecycle hook for memory leak not to occur as shown below.
beforeDestroy() { this.chart.destroy(); }
If cleanup is not done before our component gets destroyed, then that memory is never going to be released. Hence, a memory leak.
Mixin support is a Vue.js feature that allows code reusability between components in Vue.js application instances and a software composition tool.
A mixin can contain any of the options that we normally include in the components and it is a JavaScript object. All content of mixin is merged options of a component when mixin is used in that component.
The benefit of mixins:
Reusability - mixins are powerful and do not repeat yourself principle is used by mixins. Global mixins are used to be applied to instances of each and every component.
The drawback of mixins:
>> code new Vue({ el: "#app", data: { items: [ { text: "itemOne" }, { text: "itemTwo"}, ] }, computed: { itemsLength() { return this.items.length } }, watch: { itemsLength (val, oldVal) { console.log('array length changed') } } })
Watch is one of the special features of Vue.js 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. In our case, the reactive data which we are observing is ‘items’. When there is a change in items, its length is calculated in a computed object whose value is cached whenever there is a change only.
Vue.js framework is a fast growing framework. It has great development tools. One of Vue.js tools in the latest VueCLI i.e. 3.x. It has one of the best JavaScript frameworks. It allows features such as State Store, Routing, Linting, Typescript and many others built-in features. It provides a great user interface for managing projects. One of the best properties is, it allows one to save projects for future use as well as initiate changes.
Vue.js has a simple and easy to understand framework. Its architecture is well defined with vast custom methods. Its awesome features such as directives, computed properties and watchers make it easier to build a web page or an application.
Vue.js framework was inspired by two of the best JavaScript frameworks; Angular and React.js. It inherited the best features of both frameworks. It is component based and uses virtual DOM like React.js which makes it unbelievably fast. Vue.js has an incredible balance of all the features including a new feature which allows adding of new components along the way.
It has an incredible, flexible framework. Vue.js allows users to write templates on HTML file, pure JavaScript file and JavaScript file while using virtual nodes. This makes it easy for developers to understand and work with. Some of the websites using Vue.js framework are the popular Github, Netflix, Xiaomi, grammarly, codeship and Adobe Portfolio.
Being currently the most popular framework, vue.js enjoys and has a resourceful ecosystem compared to both Angular and React.js. This is because of the large number of libraries from third parties.
Compared to React and Angular which were developed by two of the social network giant companies; Facebook and Google, Vue.js began as an individual project but over time it has enjoyed enormous growth. Many developers have embraced and actually adopted it. Vue’s suitability for large scale applications has led to it being adopted by big companies such as Alibaba and Adobe.
Vue’s reactive two-way binding is one of its most distinctive features. Incorporation of Virtual DOM together with the two-way binding has minimized the amounts of code needed to be written by developers. In vue.js, a developer only need to make changes to the view layer or the Model layer and Vue’s framework will make the necessary changes in all the other layers. Its ability to keep codes in-synchronization across the entire application has been one most amazing feature. No one likes tedious work when you can just adopt Vue that performs most of the work on its own. The ability to keep data in-sync ensures data consistency and saves a lot of time and costs which would have been spent on phase-testing and debugging.
Lastly, Vue’s concise documentation provides a one-step solution to any imminent problems. The documentation provides an overview of the framework, information on installation process as well as a comparison with other frameworks. Such information is vital as it acts as guides for beginners.
A proxy is a server that acts as a doorway between the app and the internet. It forwards client’s or users’ requests to the resources. Most Vue applications are being run in serverless modes nowadays. To achieve the serverless mode, the Vue assets are stored in S3 bucket for the static web hosting.
To proxy API requests, let’s take an example of a Node.js server. The server is running on a localhost:4040. Proxying it to ensure it is accessible from the components involves the use of vue.config.js file configuration. We will include a section of devServer.
The Vue configuration will look like the one shown below:
devServer: { proxy: { ‘/api’: { Target: ‘http://localhost:4040/api’, ChangeOrigin: true } } } }
Key attributes permit Vue to keep track of every Vnode. This occurs during rendering and the key values must be distinctive from each other as this is how they are identified. When key attributes are not used and the data in the list alters the virtual DOM, the nodes are patched to reflect the alterations. This phenomenon is what developers refer to as default and efficient mode. Also when there is a new input value on the keys, the elements will be rearranged as per the keys input rather than being patched and when the keys are removed or deleted then the corresponding elements will be destroyed and exterminated.
As shown above, the parent component renders a list to the three child component nodes. When the key attributed is not used for an example resorting, Vue will automatically patch the already present nodes. This only works when the user has not inputted new data. When a user inputs new data, let say at box three, when there is resorting, the other two will remain intact while that in box three will display what the user has keyed in. this due to the fact that Vue cannot identify the data in box 3 and simply the updated data.
Key attributes may also be used to conditionally render elements to signal Vue of a unique element so that elements are not repatched.
Key is among the important Vue attributes. Key attributed is neither a directive nor a prop nor a slot nor a life cycle hook nor watchers but still remains as one of the significant attributes. Since Vue does the heavy lifting, here is where Key attributes come into play.an index cannot be used as a Key. This is what many developers fail to understand. Index is not object specific for example;
Const people = [
{ name: ‘Trent’, age: 23 }, { name: ‘john’, age: 27 }, { name: ‘Claire’, age: 44 }, ];
When we render the list to display the indexes;
<ul> <li v-for=”(person, index) in people” :key=”index”> {{ person.name }} – {{ index }} </li> </ul>
The output from the above code will be:
Trent – 0 John – 1 Claire – 2
If we try and remove one of the objects say john we will get an output similar to this;
Trent – 0 Claire – 1
After the change, Trent remains with his earlier index 0 while Claire who initially had index 2 now has index 1 instead of using the initial index 2. John who initially occupied index 1 was removed and the component got deleted once the list was updated.
From such an incident, Vue requires the use of unique IDs as the Key. If we would have used unique IDs, here is how it would have looked like:
Const people = [ { id: ‘a-unique-id’, name: ‘Trent’, age: 23 }, { id: ‘unique-id’, name: ‘John’, age: 27 }, { id: ‘last-unique-id’, name: ‘Claire’, age: 44 }, ];
Rendering:
<ul> <li v-for=”person in people” :key=”person.id”> {{ person.name }} – {{ person.id }} </li> </ul>
The example above will output a result as below:
Trent – a-unique-id John – unique-id Claire – last-unique-id
If we remove john from the list, we get:
Trent- a-unique-id Claire – last-unique-id
From an earlier example, Vue was a little confused on what to do but using unique ids allows Vue to identify which data to keep when one component from the list is removed.
Using unique IDs is of huge significance in Vue as it can also be used to add new data to a list. Vue will be aware that it only needs to create a new component and input it into the list at the correct place.
Vue.js reactivity is one of its most distinctive features. The states of its components are JavaScript reactive objects. Reactivity is the ability to adjust accordingly to changes. A perfect example of this in the day to day activities is the spreadsheet. Reactivity is a programming concept that is centered on flow of data and the dissemination of change. The use of this paradigm has enabled developers to adjust to change declaratively.
The value of cell A2 is defined by a formula A2 = A0 + A1 which gives us a result. If we update either of the cells the answer produced will be a reflection of the changes
JavaScript does not function in the same manner. JavaScript works on the base of written codes with some defined parameters. Vue.js as a product of JavaScript is very reactive. It is susceptible to change at any stage of a project. In the case of an imminent change, Vue components automatically update and re-renders. Vue uses getters and setters to detect change and act accordingly. Getters and setters are not visible to the user. They facilitate Vue to perform dependency tracking and the detection of change. An example shown below illustrates Vue’s reactivity:
Var app = new Vue({ el: ‘#app’, data: { message: “Hello World” } }); setTimeout(function() { app.message = “Nice Day”; },2000)
Renders:
<div id=”app”> <…..renders as “Hello World”….> <….then after 2seconds re-renders as “Nice Day”> {{ message }} </div>
“Message” data property is reactive. That is they will initiate a re-render if altered.
As much as Vue is very reactive, it is prone to challenges and issues. While updating and re-rendering, Vue cannot detect change in object property or deletion of components. This is due to it being a JavaScript component.
Vue also cannot identify modification of arrays which necessitates the need for vue.set use. Many of these challenges were experienced in Vue 2 and the emergence of Vue 3 has solved most of those challenges. In Vue 3 the reactive APIs were rewritten to solve the shortcoming resulting from Vue 2.
Two-way data binding using Vue is one of the most complex steps in the development of apps. Synchronization of user data had been for a longer time an uphill task to achieve for many developers. Thanks to the v-model, all those worries and nights of wondering what to do to achieve it. The v-model makes it easy to perform two-way binding.
Vue.js implements the v-model to bind data. Given an input, v-model pays attention to the input data and updates instantly on the view. It also updates the view template if there is change. This process is what is referred to as two-way binding. We can say it involves two major steps:
Below is an example of how two-way binding is implemented;
<Dev id="app"> {{Message}} <Input v-model="message"> </Dev> <Script type="text/javascript"> Var message = 'Vue. J's is rad'; New Vue ({ el: '#app', data {{message }};; </Script>
Compared to plain javascript and jQuery libraries, Vue’s library provides an easy technique of achieving two-way data binding. While using an HTML page, this is how two-way data binding can be achieved:
Var app = new Vue ({ el: ‘#app’, data: { name: “Rajesh Bhagia” } });
An instance with data property “name” is used. A default value name, ‘Rajesh Bhagia’ is used.
We use a v-model directive to bind the text-box value to the data property. We will use curly brackets to show the name property value.
<div id="app"> <h3>Your Name is : {{name}}</h3> <input type="text" v-model="name"/> </div>
A combined code looks like this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <!-- development version, includes helpful console warnings --> <script src="https://cdn.jsdelivr.net/npm/Vue/dist/vue.js"></script> </head> <body> <div id="app"> <h3>Your Name is : {{name}}</h3> <input type="text" v-model="name"/> </div> </body> <script type="text/javascript"> var app = new Vue({ el: '#app', data: { name: "Rajesh Bhagia" } }); </script> </html>
When the data-box value is changed, the value of the data property will immediately be changed as well and as an effect of reactivity, the display value will also change. The code will output as below:
Virtual DOM is an object oriented javascript that is used to represent Document Oriented Model. Several development libraries have implemented the use of Virtual DOM and Vue.js is not exceptional. In a diagrammatic form is shown below of how virtual DOM works;
A pseudo-code of how to represent DOM nodes is shown below. The pseudo-code can be referred to as a virtual DOM structure.
//an ordered list represents as JavaScript Let domNode = { Tag: ‘ul’, Attributes: { id: ‘my Id’ }, Children: [ //where the LI’s would go ] };
Use of virtual nodes in such a manner is quite affordable compared to how expensive it is to perform an update on the virtual nodes. It is more efficient to perform updates this way. A lot of time is saved compared to updating every single virtual node.
Virtual DOM is a performance enhancer as well as improved functionality. For instance, with vue.js there is no need for an HTML template or a template property for that case since the use of render() method in vue.js which outputs virtual nodes
A plugin is a set of code or software that is added to a program or installed in a system to enhance its functionality. In Vue, the sole purpose of plugins is to enable developers to build and add both local and global level functionalities to an application.
Vue plugins have several uses. Distribution of application components and addition of extra features such as routing and immutable data sources are just a few of the many uses. The simplicity and ease of use are two of the most notable features of Vue plugins. VueFire plugin used for adding firebase methods and binding to an entire application is an example of one of the commonly used plugin. Other plugins are Vuetify, VuePress, VueTour, VueX and Vee-charJS. Installing a plugin involves the use of a pseudo-code shown below;
A plugin imposes an install() method or acts as an install function in itself. The function accesses the app instance along with any other additional options.
Plugins are extremely useful in registering one or several global components or customized directives in the form of app.component() and app.directive(). They are also important in making resources injectable in an application by using an app.provide() calling.
The most common way of rendering texts is by use of mustache syntax tags. An attempt to render an HTML would result in a series of text strings which would not be parsed. The use of v-html directive has allowed developers to render and parse raw html content.
<template> <div v-html="legacySystemHTML"> </div> </template> <script> export default { data() { return { // Just like JSX! Oh wait... legacySystemHTML: ` <FONT color="#faddad" size="-2"> <MARQUEE>Please enter your name to continue.</MARQUEE> ... </FONT> ` } } } </script>
The above example when successfully run confirms how to render raw HTML to a template using v-html. If the legacySystemHTML is updated, HTML will also update accordingly.
The use of v-html is not always recommended unless one is aware of the risks associated with its use. If v-html is carelessly used, it may expose an application or a web page to attack by malicious codes executed from external sources. An understanding of this is a great advantage for a developer.
Dynamically rendering of HTML on applications exposes the apps and websites to XSS vulnerabilities. XSS vulnerabilities are very common. XSS vulnerabilities occur when inputs reaching web applications are not validated, and output to the browser is not properly escaped before being displayed and It does not know which information to trust and which not to trust. An attacker may inject a malicious code through sending it to another user on the website and since the user’s browser does not know what it should trust, it executes the code exposing its vulnerabilities. Once executed, the attacker will have access to the user’s private information stored on the browser.
As seen above, any website that depends on user-generated data may be vulnerable to XSS injections. For example websites like twitter which depend on short messages from users. It had XSS vulnerability; it would be susceptible to cyber-attacks through the injection of malicious codes in the message. Once the other user being sent the message opens the message, their browser will be infected with the malicious code.
Commonly referred to as mixin support; it is a powerful Vue.js feature that allows developers to reuse code properties in an application and software. Mixin’s major function is to prevent DRY (do not repeat yourself). Mixins are widely used in vue.js. They can be used with all the instances for example when used with a global instance they are referred to as global mixin. The use of SASS CSS preprocessor illustrates the use of mixins in development.
The usefulness of mixins comes into play when coding in a functional style. This is because functional programming is basically about creating a code that can be easily understood simply by removing the moving components. Mixins make use of encapsulation. A unique example is a a component that is supposed to toggle a state Boolean, a modal and tooltip. In this example, the tooltip and the modal do not share a lot only their way of functionality. They neither visually look similar nor are used in the same way; they are just used because of their similar logic.
Const Modal = { Template: ‘#modal’, data() { Return { isShowing: false } }, Methods: { toogleShow() { this.isshowing = !this.isShowing: } }, Components: { appChild: child } } //tooltip Const Tooltip = { Template: ‘#tooltip’, data() { Return { IsShowing: false } }, Methods: { toogleShow () { this.isShowing = !this.isShowing; } }, Components: { appChild: child } }
The logic could be extracted to create a reusable component as shown below;
Const toggle = { data () { Return { isShowing: false } }, Methods: { toggleShow () { this.isShowing = !this.isShowing; } } } Const Modal = { Template: ‘#modal’, Mixins: [toggle], Components: { appChild: child } };
Despite mixins being powerful Vue tools, they pose great danger if not carefully used. Just like all the other injected codes, mixin should be carefully used to prevent applications from misbehaving and reduce maintenance issues. It is also symbolic to say that mixin is selfish. They do not extend their services to the neighboring functions. Mixins use functions that solely alter areas within their defined scope. The use of global mixin should be regulated. Continuous use of global mixins on individual components leads to maintenance issues on continuous growing apps. Also regular ejectment of mixins to components may cause maintenance issues in the long run.
Memory leaks in vue.js applications are mostly caused by the use of third party libraries. Third party libraries have a feature of creating their own instances that manipulate the DOM which then causes the v-if directive and Vue router to exterminate all Vue instance components. After the use of third party libraries, manual cleaning should be done. The cleaning should be done in the beforeDestroy() lifecycle hook.
Improper use of global variables may also result in some unreleased memory. This may result in memory leaks due to dereference. Also direct referencing of native methods in windows have a consequence of referencing the DOM elements which makes memory not to be released. Below is a basic example:
For example, we use a fictional library, PowerGraph.js, inside the component. It creates a graph instance which displays data on the page:
mounted() { this.chart = new PowerGraph(); }
It is required to call the graph instance’s destroyed () method if it’s provided, or it is vital to implement own cleanup method of our own
beforeDestroy() { this.chart.destroy(); }
If cleanup is not accomplished before our component is destroyed, that memory will never be released. Hence, a memory leak.
Directives in Vue.js are HTML’s special attributes that allow the manipulation of DOM (Document Object Model). They are commonly used as they provide powerful functionalities.
Below are some of the most commonly used Vue.js directives:
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.
<p v-if="isLoggedOut">You are logged out</p>
V-else - it is a directive which is used to to remove or add DOM elements only when condition in v-if it is preceded by evaluates to false. We do not have to pass any value and it follow v-if or v-else-if directives.
<p v-if="isLoggedOut">You are logged out</p> <p v-else>You are logged in</p>
V-else-if - it is a directive which we are in need of when there are more than two conditions to be checked for addition or removal of DOM element. It is preceded by v-if directive and followed by v-else directive.
<p v-if="isLoggedOut">You are logged out</p> <p v-elese-if="noLogoutButton">There is no logout button</p> <p v-else>You are logged in</p>
V-show - it is similar to the v-if directive as it is concerned with showing or hiding of 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.
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>
Why is the usage of v-if and v-for on the same element not recommended in Vue.js, what are the two tempting cases and how should we get rid of the temptation?
The V-for directive has higher priority than the v-if directive and caution must be taken when using those two on the same element. When using the two directives there are two main cases where the usage is tempting. The two cases are:
For the first case, we have to use a computed property that filters the items in the list and a new assignment to a new property so that we can get rid of the temptation.
For the second case, the v-if directive has to be moved to the container element the condition is to show is first checked before the list is generated as if the v-for directive precedes the v-if the list would be generated first without filtering as the v-for has higher priority than the v-if directive.
First one:
<template> <ul v-if="complete"> <TodoItem v-for="todo in todos" :todo="todo" /> </ul> <TodoItem v-for="todo in shownTodos" :todo="todo" />
Second one:
<TodoItem v-if="complete" v-for="todo in todos" :todo="todo" />
Third one:
<TodoItem v-for="todo in todos" v-if="todo.shown" :todo="todo" />
First one is a good practice since the v-if directive is moved to the container element when the list items are to be generated if they are completed. Therefore v-for has no priority here and nothing leads to temptation
Second one is a bad practice. It is tempting since v-for and void are being used on the same element. V-if should be written in the wrapper component so that the temptation is removed.
Third one is also a bad practice as we are filtering elements of the list by using v-for and v-if on the same element; rather it is recommended to use computed properties for such functionalities.
Event handlers - provide a mechanism by which an event is controlled and what happens to an event is decided. In Vue.js v-on directive is used for event handling and a value assigned to it the program can either be an expression for simpler computations or a method name for complex computations which are triggered on the occurrence of an event.
Coding demonstration
<div id="example-2"> <!-- `greet` is the name of a method defined below --> <button v-on:click="greet">Greet</button> </div> var example2 = new Vue({ el: '#example-2', data: { name: 'Vue.js' }, // define methods under the `methods` object methods: { greet: function (event) { // `this` inside methods points to the Vue instance alert('Hello ' + this.name + '!') // `event` is the native DOM event if (event) { alert(event.target.tagName) } } } })
>> Output >> Result after ‘Greet’ button is clicked
In Vue.js 2.x version, only a single root element is allowed for a component. In case there are multiple elements in the template all should be wrapped with the parent element as shown below with an example.
<template> <div class="todo-item"> <h2>{{ title }}</h2> <div v-html="content"></div> </div> </template>
But in Vue.js 3. x version the components are allowed to have multiple root nodes or fragments.
<template> <h2>{{ title }}</h2> <div v-html="content"></div> </template>
SFC (Single File Components) is a special file format in Vue that provides encapsulation of the template, logic, and styling of a component in a single file. They are used to solve the common issues of JavaScript-driven applications with a .vue extension. Below is an example of SFC:
<script> export default { data() { return { greeting: 'Hello World!' } } } </script> <template> <p class="greeting">{{ greeting }}</p> </template> <style> .greeting { color: red; font-weight: bold; } </style>
Following is a list of problems that are addressed by Single File Components in Vue.js:
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.
There are two different ways of creating filters:
filters: { capitalize: function (value) { if (!value) return '' value= value.toString() return value.charAt(0).toUpperCase() + value.slice(1) } }
Vue.filter('capitalize', function (value) { if (!value) return '' value = value.toString() return value.charAt(0).toUpperCase() + value.slice(1) }) new Vue({ // ... })
In both of the above cases, the value of the data is the same but its rendering to the browser is the only thing that is changed.
Life cycle hooks - are functions giving users a chance to add certain functionality at a specific stage as each instance of the Vue component passes through a series of stages starting from its initialization.
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 a specific stage.
All events or hooks a Vue instance goes through is listed below:
Vue Router is an official router of Vue.js as it is integrated with Vue.js core and is used in building Vue.js applications that are on a single page.
Important features provided by Vue Router are listed below:
To render raw HTML in a Vue.js template developers have to implement the v-HTML attribute. Reference to an HTML string in the data option is passed to the v-HTML attribute in the template as a value.
Therefore, the raw HTML will be rendered into the component having the v-HTML attribute.
Look at the following code, when there is any modification in the HTML property that is in the data option, the HTML to be injected in the template updates the template accordingly.
<template> <div v-html="legacySystemHTML"> </div> </template> <script> export default { data() { return { legacySystemHTML <FONT color="#faddad" size="-2"> <MARQUEE>Please enter your name to continue.</MARQUEE> </FONT> } } } </script>
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.
Expect to come across this popular question in Vue.js technical interview questions.
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, the 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 the 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) } })
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.
It's no surprise that this one pops up often in Vue.js interview questions.
Directive is a piece of instruction to perform a certain task. In vue.js a directive is a sign that directs the library to perform an action to the DOM. Directives in Vue.js are much simpler to understand compared to 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.
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.
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> 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.
A common interview question on Vue.js, don't miss this one.
Vue instances undergo a lot of processes from the moment they are initialized to the point where they are wrecked and exterminated. Lifecycle in Vue is the compilation of activities from data setup and observation to compiling the template, to mounting 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”
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.
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.
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
One of the most frequently posed interview questions is Vue.js, be ready for it.
Their similarity is that both are involved in adding or removing DOM elements. What makes them different is that v-if uses conditions while v-show uses CSS properties to determine whether to add an element or not.
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).
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.
The state is an important part of Vue applications since it is concerned with how data is passed among components.
arrayName.push({ attributeName: 'value' })
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>
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:
A staple in Vue.js developer interview questions, be prepared to answer this one.
Example: tracking the position of some moving object; as 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})}}
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).
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.
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.
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:
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:
<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.
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)
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
Mutation methods alter the original array.
Following are the list of array mutation methods that initiate view updates
Below are the methods that don't mutate the original array but return a new array and are called non-mutation methods.
<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>
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.
A common question in Vue.js advanced interview questions, don't miss this one. <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.
In Vue.js component
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> <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
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:
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)
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() } }
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.
One of the most frequently posed Vue.js interview questions for experienced, be ready for it.
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)
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.`) } }
The second one is preferable performance-wise since it uses the computed property.
Computed property :
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.
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>
//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
A staple in Vue.js interview questions and answers, be prepared to answer this one.
Stateful logic - involves managing the state, which changes over time. It is concerned with data of a different state whose state changes every time.
Example: tracking the position of some moving object. As time passes, if something is in motion, then its position changes. so, we can say the position has a different state and logic performing some manipulation on the 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 pass 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).
The state is an important part of Vue applications since it is concerned with how data is passed among components.
State management is better:
const MockComponent = { props: { showMe: { type: Boolean, }, }, template: ` <div v-if="showMe"> This is a test component </div> `, }; new Vue({ el: '#app', components: { MockComponent, }, template: ` <div> <MockComponent showMe="" /> </div> `, });
>> Output
If a boolean prop exists in the child whether a value is assigned to it or not then its value will be evaluated to true. In the above code, we can see that ‘showMe’ which is a boolean prop has an assigned value which is an empty string so the value of the ‘showMe’ will be true. And there will not be any error in the output.
If ‘<MockComponent />’ was replaced by ‘ <MockComponent showMe="" />’ in the above code then since ‘showMe’ does not exist, the value of the boolean prop would have been false. Therefore, there would not have been anything printed on the screen.
Memory leak 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 own instances.
In order for memory leaks not to occur, we have to manually clean up any third-party instances in beforeDestroy() lifecycle hook.
Example:
mounted() { this.chart = new PowerGraph(); }
When the component is mounted, a third-party library is created so it has to be destroyed in beforeDestroy() lifecycle hook for memory leak not to occur as shown below.
beforeDestroy() { this.chart.destroy(); }
If cleanup is not done before our component gets destroyed, then that memory is never going to be released. Hence, a memory leak.
Mixin support is a Vue.js feature that allows code reusability between components in Vue.js application instances and a software composition tool.
A mixin can contain any of the options that we normally include in the components and it is a JavaScript object. All content of mixin is merged options of a component when mixin is used in that component.
The benefit of mixins:
Reusability - mixins are powerful and do not repeat yourself principle is used by mixins. Global mixins are used to be applied to instances of each and every component.
The drawback of mixins:
>> code new Vue({ el: "#app", data: { items: [ { text: "itemOne" }, { text: "itemTwo"}, ] }, computed: { itemsLength() { return this.items.length } }, watch: { itemsLength (val, oldVal) { console.log('array length changed') } } })
Watch is one of the special features of Vue.js 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. In our case, the reactive data which we are observing is ‘items’. When there is a change in items, its length is calculated in a computed object whose value is cached whenever there is a change only.
Vue.js framework is a fast growing framework. It has great development tools. One of Vue.js tools in the latest VueCLI i.e. 3.x. It has one of the best JavaScript frameworks. It allows features such as State Store, Routing, Linting, Typescript and many others built-in features. It provides a great user interface for managing projects. One of the best properties is, it allows one to save projects for future use as well as initiate changes.
Vue.js has a simple and easy to understand framework. Its architecture is well defined with vast custom methods. Its awesome features such as directives, computed properties and watchers make it easier to build a web page or an application.
Vue.js framework was inspired by two of the best JavaScript frameworks; Angular and React.js. It inherited the best features of both frameworks. It is component based and uses virtual DOM like React.js which makes it unbelievably fast. Vue.js has an incredible balance of all the features including a new feature which allows adding of new components along the way.
It has an incredible, flexible framework. Vue.js allows users to write templates on HTML file, pure JavaScript file and JavaScript file while using virtual nodes. This makes it easy for developers to understand and work with. Some of the websites using Vue.js framework are the popular Github, Netflix, Xiaomi, grammarly, codeship and Adobe Portfolio.
Being currently the most popular framework, vue.js enjoys and has a resourceful ecosystem compared to both Angular and React.js. This is because of the large number of libraries from third parties.
Compared to React and Angular which were developed by two of the social network giant companies; Facebook and Google, Vue.js began as an individual project but over time it has enjoyed enormous growth. Many developers have embraced and actually adopted it. Vue’s suitability for large scale applications has led to it being adopted by big companies such as Alibaba and Adobe.
Vue’s reactive two-way binding is one of its most distinctive features. Incorporation of Virtual DOM together with the two-way binding has minimized the amounts of code needed to be written by developers. In vue.js, a developer only need to make changes to the view layer or the Model layer and Vue’s framework will make the necessary changes in all the other layers. Its ability to keep codes in-synchronization across the entire application has been one most amazing feature. No one likes tedious work when you can just adopt Vue that performs most of the work on its own. The ability to keep data in-sync ensures data consistency and saves a lot of time and costs which would have been spent on phase-testing and debugging.
Lastly, Vue’s concise documentation provides a one-step solution to any imminent problems. The documentation provides an overview of the framework, information on installation process as well as a comparison with other frameworks. Such information is vital as it acts as guides for beginners.
A proxy is a server that acts as a doorway between the app and the internet. It forwards client’s or users’ requests to the resources. Most Vue applications are being run in serverless modes nowadays. To achieve the serverless mode, the Vue assets are stored in S3 bucket for the static web hosting.
To proxy API requests, let’s take an example of a Node.js server. The server is running on a localhost:4040. Proxying it to ensure it is accessible from the components involves the use of vue.config.js file configuration. We will include a section of devServer.
The Vue configuration will look like the one shown below:
devServer: { proxy: { ‘/api’: { Target: ‘http://localhost:4040/api’, ChangeOrigin: true } } } }
Key attributes permit Vue to keep track of every Vnode. This occurs during rendering and the key values must be distinctive from each other as this is how they are identified. When key attributes are not used and the data in the list alters the virtual DOM, the nodes are patched to reflect the alterations. This phenomenon is what developers refer to as default and efficient mode. Also when there is a new input value on the keys, the elements will be rearranged as per the keys input rather than being patched and when the keys are removed or deleted then the corresponding elements will be destroyed and exterminated.
As shown above, the parent component renders a list to the three child component nodes. When the key attributed is not used for an example resorting, Vue will automatically patch the already present nodes. This only works when the user has not inputted new data. When a user inputs new data, let say at box three, when there is resorting, the other two will remain intact while that in box three will display what the user has keyed in. this due to the fact that Vue cannot identify the data in box 3 and simply the updated data.
Key attributes may also be used to conditionally render elements to signal Vue of a unique element so that elements are not repatched.
Key is among the important Vue attributes. Key attributed is neither a directive nor a prop nor a slot nor a life cycle hook nor watchers but still remains as one of the significant attributes. Since Vue does the heavy lifting, here is where Key attributes come into play.an index cannot be used as a Key. This is what many developers fail to understand. Index is not object specific for example;
Const people = [
{ name: ‘Trent’, age: 23 }, { name: ‘john’, age: 27 }, { name: ‘Claire’, age: 44 }, ];
When we render the list to display the indexes;
<ul> <li v-for=”(person, index) in people” :key=”index”> {{ person.name }} – {{ index }} </li> </ul>
The output from the above code will be:
Trent – 0 John – 1 Claire – 2
If we try and remove one of the objects say john we will get an output similar to this;
Trent – 0 Claire – 1
After the change, Trent remains with his earlier index 0 while Claire who initially had index 2 now has index 1 instead of using the initial index 2. John who initially occupied index 1 was removed and the component got deleted once the list was updated.
From such an incident, Vue requires the use of unique IDs as the Key. If we would have used unique IDs, here is how it would have looked like:
Const people = [ { id: ‘a-unique-id’, name: ‘Trent’, age: 23 }, { id: ‘unique-id’, name: ‘John’, age: 27 }, { id: ‘last-unique-id’, name: ‘Claire’, age: 44 }, ];
Rendering:
<ul> <li v-for=”person in people” :key=”person.id”> {{ person.name }} – {{ person.id }} </li> </ul>
The example above will output a result as below:
Trent – a-unique-id John – unique-id Claire – last-unique-id
If we remove john from the list, we get:
Trent- a-unique-id Claire – last-unique-id
From an earlier example, Vue was a little confused on what to do but using unique ids allows Vue to identify which data to keep when one component from the list is removed.
Using unique IDs is of huge significance in Vue as it can also be used to add new data to a list. Vue will be aware that it only needs to create a new component and input it into the list at the correct place.
Vue.js reactivity is one of its most distinctive features. The states of its components are JavaScript reactive objects. Reactivity is the ability to adjust accordingly to changes. A perfect example of this in the day to day activities is the spreadsheet. Reactivity is a programming concept that is centered on flow of data and the dissemination of change. The use of this paradigm has enabled developers to adjust to change declaratively.
The value of cell A2 is defined by a formula A2 = A0 + A1 which gives us a result. If we update either of the cells the answer produced will be a reflection of the changes
JavaScript does not function in the same manner. JavaScript works on the base of written codes with some defined parameters. Vue.js as a product of JavaScript is very reactive. It is susceptible to change at any stage of a project. In the case of an imminent change, Vue components automatically update and re-renders. Vue uses getters and setters to detect change and act accordingly. Getters and setters are not visible to the user. They facilitate Vue to perform dependency tracking and the detection of change. An example shown below illustrates Vue’s reactivity:
Var app = new Vue({ el: ‘#app’, data: { message: “Hello World” } }); setTimeout(function() { app.message = “Nice Day”; },2000)
Renders: