Vue JS FAQs

Kishan Patel
Francium Tech
Published in
15 min readApr 11, 2020

--

A JavaScript framework for building user interfaces and single-page app

How to create a Vue project

Check out here for more information.

Check out Vue CLI docs to learn about @vue/cli.

What are the major features of VueJS?

Below are some of the major features available with VueJS

  1. Virtual DOM: Virtual Dom is just simply a JavaScript object which represents the Document Object Model(DOM). This is a lightweight in-memory tree representation of the original HTML DOM and is updated without affecting the original DOM.
  2. Components: Used to create reusable custom elements in VueJS applications.
  3. Templates: VueJS provides HTML-based templates that bind the DOM with the Vue instance data.
  4. Routing: Navigation between pages is achieved through vue-router
  5. Lightweight: VueJS is a lightweight library compared to other frameworks.

What are the lifecycle methods of VueJS?

Through lifecycle methods, you can hook into a component so that you will know when your component is created, added to the DOM, updated, or destroyed.

These are the lifecycle methods with sequence

  • beforeCreate
  • data
  • created
  • beforeMount
  • mounted
  • beforeUpdate
  • updated
  • activated
  • deactivated
  • beforeDestroy
  • destroyed
  • errorCaptured

The best practice of writing code sequence.

What are the conditional directives?

  • v-if
  • v-else-if
  • v-else
  • v-show

How to create a new Vue instance?

  • Vue 2
import Vue from 'vue';

new Vue({
el: '#root',
router: new VueRouter({
mode: 'history',
routes: [
{
path: '/',
component: someComponent
}
]
})
data: {},
...
})
  • Vue 3
import { createApp } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';

const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
component: someComponent
}
]
})

const app = createApp({
data() {
return {}
},
...
})
app.use(router);

app.mount("#root")

What are the components and give an example?

Components are reusable Vue instances with a name. They accept the same options as new Vue, such as data, computed, watch, methods, and lifecycle hooks(except a few root-specific options like el)

e.g.

Created Vs mounted

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

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

console.log(element.innerHTML)

Why key attributes?

  • To track each node’s identity and to make sure each element are independent and doesn’t impact each other.

Why should not use if and for directives together on the same element?

It is recommended not to use v-if on the same element as v-for. Because v-for directive has a higher priority than v-if. There are two cases where developers try to use this combination,

  • To filter items in a list For example, if you try to filter the list using a v-if tag,

This can be avoided by preparing the filtered list using the computed property on the initial list

  • To avoid rendering a list if it should be hidden For example, if you try to conditionally check if the user is to be shown or hidden
  • This can be solved by moving the condition to a parent by avoiding this check for each user

How do you use v-for directive with a range?

You can also use integer type(say ’n’) for a v-for directive which repeats the element many times.

<div>
<span v-for="n in 20">{{ n }} </span>
</div>

What are the event modifiers provided by vue?

Normally, javascript provides event.preventDefault() or event.stopPropagation() inside event handlers. You can use methods provided by vue, but these methods are meant for data logic instead of dealing with DOM events. Vue provides below event modifiers for v-on and these modifiers are directive postfixes denoted by a dot.

  1. .stop
  2. .prevent
  3. .capture
  4. .self
  5. .once
  6. .passive

What are key modifiers?

Vue supports key modifiers on v-on for handling keyboard events. Let's take an example of keyup event with enter keycode.

<!-- only call `vm.show()` when the `keyCode` is 13 -->
<input v-on:keyup.13="show">

Remembering all the key codes is really difficult. It supports the full list of key codes aliases

  1. .enter
  2. .tab
  3. .delete (captures both “Delete” and “Backspace” keys)
  4. .esc
  5. .space
  6. .up
  7. .down
  8. .left
  9. .right

e.g.

<input v-on:keyup.enter="submit">
// (OR)
<!-- with shorthand notation-->
<input @keyup.enter="submit">

What is the use of $parent and $root?

In every subcomponent of a new Vue instance, this root instance can be accessed with the $root property.

Similar to $root, the $parent property can be used to access the parent instance from a child. This can be tempting to reach for as a lazy alternative to passing data with a prop.

Check out my example on JS Fiddle.

$refs

Refs are Vue instance properties used to register or indicate a reference to HTML elements or child elements in the template of your application.

What are the supported System Modifier Keys?

Vue supports below modifiers to trigger mouse or keyboard event listeners when the corresponding key is pressed,

  1. .ctrl
  2. .alt
  3. .shift
  4. .meta

e.g.

<div @click.ctrl="doSomething">Do something</div>

What are the supported Mouse Button Modifiers?

Vue supports below mouse button modifiers

  1. .left
  2. .right
  3. .middle

e.g.

<button v-if="button === 'right'" v-on:mousedown.right="increment" v-on:mousedown.left="decrement" />

One-way data binding

In one-way databinding, the value of the Model is used in the View (HTML page) but you can’t update Model from the View

How do you implement two-way data binding?

You can use the v-model directive to create two-way data bindings on form input, textarea, and select elements. Let's take an example of it using input component,

<input v-model="message" placeholder="Enter input here">
<p>The message is: {{ message }}</p>

What are the supported modifiers on model?

There are three modifiers supported for v-model directive.

  1. lazy: By default, v-model syncs the input with the data after each input event. You can add the lazy modifier instead of sync after change events.
<!-- synced after "change" instead of "input" -->
<input v-model.lazy="msg" >

2. number:

<input v-model.number="age" type="number">

3. trim: Removed whitespace from user input automatically

<input v-model.trim="msg">

How do you implement model on custom input components?

The custom events can also be used to create custom inputs that work with v-model. The inside the component must follow below rules,

  1. Bind the value attribute to a value prop
  2. On input, emit its own custom input event with the new value. Let’s take a custom-input component as an example,

Depending on the element, Vue decides how to listen and handle the data. For input elements, you might use v-model like this:

<input v-model="email" />
// v-model translates to this:
<input :value="email" @input="e => email = e.target.value" />

Example:

Vue.component('custom-input', {
props: ['value'],
template: `
<input
v-bind:value="value"
v-on:input="$emit('input', $event.target.value)"
>
`
})

// Now you can use v-model with this component,

<custom-input v-model="searchInput"></custom-input>

Another Example

Check here for more examples.

What are the possible prop types?

You can declare props with type or without type. But it is recommended to have prop types because it provides the documentation for the component and warns the developer for any incorrect data type being assigned.

Define props without type:

props: [‘name’, ‘age’,…],

Define props with type:

Props with multiple types,

props: {
identityNumber: [String, Number],
}
-OR-
props: {
identityNumber: {
type: [String, Number],
default: 123
}
}

Props Validation

When designing a large-scale project, it’s easy to forget exactly the exact format, type, and other conventions you used for a prop.

Watch property

watch: {
// whenever question changes, this function will run
question(newQuestion, oldQuestion) {
if (newQuestion.includes('?')) {
this.getAnswer()
}
}
},

How to know if router param changed?

watch: {
'$route' (to, from) {
// react to route changes...
}
}
-OR-
beforeRouteUpdate (to, from, next) {
// react to route changes and then call next()
}

Checkout more on watch.

What are the filters?

Filters can be used to apply common text formatting. These Filters should be appended to the end of the JavaScript expression, denoted by the “pipe” symbol. You can use them in two specific cases:

  1. mustache interpolations
  2. v-bind expressions

For example, Let’s define a local filter named capitalize in a component’s options

filters: {
capitalize: function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
}
}

Now you can use the filter in either mustache interpolation or v-bind expression,

<!-- in mustaches -->
{{ username | capitalize }}
<!-- in v-bind -->
<div v-bind:id="username | capitalize"></div>

How do you chain filters?

You can chain filters one after the other to perform multiple manipulations on the expression. The generic structure of the filter chain would be as below,

{{ message | filterA | filterB | filterB ... }}

In the above chain stack, you can observe that message expression applied with three filters, each separated by a pipe(|) symbol. The first filter(filterA) takes the expression as a single argument and the result of the expression becomes an argument for the second filter(filterB) and the chain continues for remaining filters.

How to pass parameters to filters?

{{ message | filterA('arg1', arg2) }}

What are mixins?

Mixin gives us a way to distribute reusable functionalities in Vue components. These reusable functions are merged with existing functions. A mixin object can contain any component options. Let us take an example of mixin with created lifecycle which can be shared across components,

const myMixin = {
created(){
console.log("Welcome to Mixins!")
}
}
var app = new Vue({
el: '#root',
mixins: [myMixin]
})

What is the purpose of keep-alive tag?

Keep-alive tag is an abstract component used to preserve component state or avoid re-rendering.

<!-- Inactive components will be cached! -->
<keep-alive>
<component v-bind:is="currentTabComponent"></component>
</keep-alive>

What is the purpose of vuejs once directive?

If you want to render a lot of static content then you need to make sure it only evaluated once and then cached thereafter. In this case, you can use v-once directive by wrapping at the root level. The example usage of v-once directive would be as below,

Vue.component('legal-terms', {
template: `
<div v-once>
<h1>Legal Terms</h1>
... a lot of static content goes here...
</div>
`
})

v-memo

It will re-render the component only if the dependency array value is changed.

<p v-memo="[msg, count]">
{{ msg }} | {{ count }}
</p>
// If you have empty dependency array means that is equivalent to v-once
<p v-memo="[]">
Some static information
</p>
// same aas above one
<p v-once>
Some static information
</p>

slot

Example 1:

// Parent component
<submit-button>
Save
</submit-button>

// Child component submit-button.vue
<button type="submit">
<slot></slot>
</button>

Example 2:

// Parent component
<submit-button></submit-button>

// Child component with default fallback submit-button.vue
<button type="submit">
<slot>Submit</slot>
</button>

Example 3: (named slot)

Parent:

<base-layout>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>

<p>A paragraph for the main content.</p>
<p>And another one.</p>

<template v-slot:footer>
<p>Here's some contact info</p>
</template>
</base-layout>

Child(base-layout.vue)

<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>

What is scoped CSS?

Scoped CSS is a mechanism in VueJS Single File Components(SFC) that prevents styles from leaking out of the current component and affecting other unintended components on your page. i.e, When a <style> tag has the scoped attribute, its CSS will apply to elements of the current component only. It uses PostCSS to transform scoped CSS to plain CSS. Let’s take an example usage of scoped CSS.

<style scoped>
.greeting {
color: green;
}
</style>
<template>
<div class="greeting">Let's start Scoped CSS</div>
</template>

The above code will be converted to plain CSS,

<style scoped>
.greeting[data-v-f3f3eg9] {
color: green;
}
</style>
<template>
<div class="greeting" data-v-f3f3eg9>Let's start Scoped CSS</div>
</template>

Are parent styles leaked into child components in scoped CSS?

The parent component’s styles will not leak into child components. But a child component’s root node will be affected by both the parent’s scoped CSS and the child’s scoped CSS. i.e, your child component’s root element has a class that also exists in the parent component, the parent component’s styles will leak to the child.
The scoped CSS style doesn’t impact v-html directive’s dynamically generated content.

CSS Module

First, CSS Modules must be enabled by passing modules: true to css-loader:

// webpack.config.js
{
module: {
rules: [
// ... other rules omitted
{
test: /\.css$/,
use: [
'vue-style-loader',
{
loader: 'css-loader',
options: {
// enable CSS Modules
modules: true,
// customize generated class names
localIdentName: '[local]_[hash:base64:8]'
}
}
]
}
]
}
}

In vue template:

<template>
<p :class="$style.red">
This should be red
</p>
</template>

<style module>
.red {
color: red;
}
.bold {
font-weight: bold;
}
</style>

Learn more about CSS module.

Router link

<router-link> is the component for enabling user navigation in a router-enabled app. The target location is specified with the to prop. It renders as an <a> tag with correct href by default.

What is dynamic route matching?

Sometimes it may be required to map routes to the same component based on a pattern. Let’s take a user component with the mapped URLs like /user/john/post/123 and /user/jack/post/235 using dynamic segments.

const User = {
template: '<div>User {{ $route.params.name }}, PostId: {{ route.params.postid }}</div>'
}
const router = new VueRouter({
routes: [
// dynamic segments start with a colon
{ path: '/user/:name/post/:postid', component: User }
]
})

What is Prop drilling?

Prop drilling is the idea of passing props down and down and down to child components.

There are multiple ways to avoid prop drilling.

  • Provide and Inject
  • Event Bus controller
  • Vuex

Provide & Inject

To provide data to a component’s descendants, use the provide option and to inject data provided by an ancestor component, use the inject option.

Syntax:

// parent
export default {
provide: {
message: 'hello!'
}
}


// nested child
export default {
inject: ['message'],
created() {
console.log(this.message) // injected value
}
}

Check out here for more details.

What is the event bus controller?

By default, communication between Vue components happens with the use of props. Props are properties that are passed from a parent component to a child component. To get rid out of the prop drilling you can use EventBus.

Let’s understand this from an example:

JS:

HTML template:

Check out for more information CSS Tricks.
Another good example of Event Bus.

Dynamic Component

<component v-bind:is="currentTabComponent"></component>

// - or -

<component :is="currentTabComponent"></component>

keep-alive with Dynamic Components

When switching between these components though, you’ll sometimes want to maintain their state or avoid re-rendering for performance reasons.

Send object data as props through v-bind

Set dynamic routing through addRoutes

$on(‘hook:’)

This is another nicety which I think is still is not documented yet. Often if you are using a third-party plugin or need to add a custom event listener, you first define it in created or mounted hook and then remove it in “beforeDestroy” hook. It is very important to clear out event listeners, so your code doesn’t cause memory leaks. Sometimes plugins might have a ‘destroy’ method.

With the use of $on(‘hook:) you can avoid a definition of another life-cycle hook.

Vuex..

What is vuex?

Vuex is a state management pattern + library (Flux-inspired Application Architecture) for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.

Let’s understand this through an example,

e.g.

To get language from the store and to update data on the store there are two ways

  • First way
  • Second way

Now let’s see how the sore will look like

mapState Vs. mapGetters?

Through mapState you can directly get the data from state, through mapGetters you can return some calculated state data.

e.g.

Vue javascript

Html template

mapAction Vs. mapMutation?

To update the state synchronously we should always use mapMutation instead of mapAction. We do some calculations inside mapAction after that pass the value to the mapMutation to update the state.
Learn more about mutations and actions.

What is the Vuex module?

Vuex allows us to divide our store into modules. Each module can contain its own state, mutations, actions, getters, and even nested modules.

Check out here to learn through an example.

Vue 3 new features

  • Composition API (Now built-in)
  • Multiple root elements (Template syntax )
  • Suspense
  • Multiple V-models
  • Better reactivity
  • Portals (teleport)

Teleport

<Teleport> is a built-in component that allows us to "teleport" a part of a component's template into a DOM node that exists outside the DOM hierarchy of that component.

<button @click="open = true">Open Modal</button>

<Teleport to="body">
<div v-if="open" class="modal">
<p>Hello from the modal!</p>
<button @click="open = false">Close</button>
</div>
</Teleport>

Suspense

<Suspense> is a built-in component for orchestrating async dependencies in a component tree. It can render a loading state while waiting for multiple nested async dependencies down the component tree to be resolved.

<Suspense>
<!-- component with nested async dependencies -->
<Dashboard />

<!-- loading state via #fallback slot -->
<template #fallback>
Loading...
</template>
</Suspense>

Unit test…

Mount vs shallowMount

Mount will render the current component with all children and also child of each children presents in the component. The entire rendered tree can get really big. Repeatedly rendering all child components could slow down our tests, to get rid out of this problem we can use shallowMount.
shallowMount will render only current component.

Optimise page load performance

  • Check memory leak : Memory leaks can lead to increased memory usage over time, causing degraded performance and potentially crashes. Remove event listeners on beforeDestroy.
  • Minimize Render and Update Cycles by using v-once for static sections and use v-memo if required.
  • Use Computed Properties and Memoization: Computed properties can cache results and only recompute when their dependencies change. Utilize them to avoid redundant computations.
  • Lazy Loading and Code Splitting: Split your application into smaller chunks and load them on demand. This technique can improve initial load times by only loading the necessary components when they are needed.
  • Asynchronous Components: Use Vue’s built-in support for asynchronous components to load components in parallel and avoid blocking the main thread. This is particularly useful for heavy components that take longer to render.
  • Consider virtual scrolling or pagination for large lists.
  • Use Webpack Bundle Analyzer: Analyze your bundle size using tools like Webpack Bundle Analyzer to identify large dependencies or unnecessary code. Eliminate unused dependencies and consider code splitting to reduce bundle size.
  • Use low-resolution images on the listing page.
  • Choosing the Right Architecture .
  • Also, check with the API side as well if it’s taking longer.

List out top 10 organizations using Vuejs?

Below are the top 10 organizations using VueJS for their applications or products,

  1. Facebook — Used on marketing side of its Newsfeed
  2. Netflix — Used in two internal apps for building movie streaming interfaces
  3. Adobe — Used for Portfolio, a custom website builder designed to help users showcase their creative work
  4. Xiaomi — Used for products where it sells from consumer electronics to software
  5. Alibaba — Provide their apps an excellent experience to its customers
  6. WizzAir — A budget airline WizzAir used for their customers user interface
  7. EuroNews
  8. Laracasts
  9. GitLab
  10. Laracasts

--

--