You are on page 1of 100

Volume 16 | Issue 05 | MAy 2021

TECHNOLOGY
YOUR HANDY GUIDE TO EVERYDAY

to

(Part - 1)

Getting started Setting up Vue Instance


Template Syntax Computed Properties
Class and Style bindings Conditional rendering
List Rendering Events

Free With Digit May 2021


Fed up of this $#!7:

Come home to

Te c h n o lo g y | S c i e n ce | G e e k C u l t u re | G a m i n g | A l l t h i n g s G e e k

geek.digit.in
e - m a g | C o m m u n i t y Fo r u m | e - DV D s | G e e k a r t i c le s a n d m o re . . .
fAST
tRACK
to

(Part - 1)

powered by
Chapters
vue.js (Part - 1)
may 2021

PAGE #

06 Things to know about Vue.js


Why is Vue.js one of the popular javascript frameworks that
web-developers are crazy about?

12 Vue.js installation
Getting started with Vue.js

22 Vue Instance
In contrast to other monolithic architectures, Vue.js is designed
from the ground up to be incrementally adoptable

30 Template Syntax
Vue.js is quite different from the way typical frameworks are
invoked

Editorial Design
Credits
The people behind this book

Chief Editor Sr. Art Director


Robert Sovereign-Smith Anil VK

Managing Editor Sr. Visualiser


Mithun Mohandas Baiju NV
Contents 3

37 Computed Properties
Why are computed properties the best for implementing
complex logic, and how can it be done?

51 Class and Style Bindings


When modifying an element’s class list and inline styles, data-
binding is required.

69 Conditional Rendering
If-else in context of Vue.js

77 List Rendering
Dynamic list rendering to provide a collection of equally
grouped items

87 Events
Events are a great way to build interactivity in your web
applications

Volume 16 | Issue 05 | mAy 2021

TECHNOLOGY
YOUR HANDY GUIDE TO EVERYDAY

© 9.9 Group Pvt. Ltd. to

(Formerly known as Nine Dot Nine Mediaworx Private Limited)

Published by 9.9 Group Pvt. Ltd. (Formerly known as Nine Dot Nine (Part - 1)

Mediaworx Private Limited). No part of this book may be reproduced,


stored, or transmitted in any form or by any means without the prior
Cover Design: baiju nv

written permission of the publisher.

May 2021
Free with Digit. If you have paid to buy this Fast Track from any source
other than 9.9 Group Pvt. Ltd. (Formerly known as Nine Dot Nine
Mediaworx Private Limited), please write to editor@digit.in with details Getting started Setting up Vue Instance
Template Syntax Computed Properties
Class and Style bindings Conditional rendering

Custom publishing
List Rendering Events

Free With Digit may 2021

If you want us to create a customised Fast Track for you in order to


demystify technology for your community, employees or students
contact editor@digit.in
4 Introduction

The Fast and the


Feature-Rich
W
eb development has been through a tumultuous ride
over the past two decades. From the initial days of Web
1.0 where web pages were painfully simple, we moved
towards making them richer and more functional. The
unfortunate downside of making richer web pages is that they tend to
become bloated and don’t run properly on a lot of devices. And the advent
of mobile devices with expensive data plans meant that heavy pages would
miss out on consumers if they didn’t load on time or if it became too expen-
sive to load. Google’s own metrics state that you stand to lose a major chunk
of visitors if your webpage doesn’t load in under two seconds.
So now we’re in an era where everything needs to load super quick and
the websites shouldn’t seem like they were designed before man discovered
fire. And thus, lean frameworks were born. We’ve had several of those over
the years. There’s React, Angular, Glimmer and many more frameworks that
have entered the market over the past 10 years with promises of building
lean and performant web sites. However, making something lean shouldn’t
take away helpful features and modules that would have aided developers
in rapid prototyping. And thus, the search for a framework that’s not only
lean but also allows for developers to build rich web sites began.
Vue.js is one of many such frameworks that lay claim to the throne of
being the best. While that’s very subjective, it can certainly be said that it’s
one of the better frameworks out there right now. Vue.js was built by Evan
You who had worked on AngularJS at Google and he designed Vue.js with
Introduction 5

the goal of extracting the best features of AngularJS. AngularJS has, over the
years, become quite bloated and, with the shifting focus of search engines
such as Google to reward faster websites, is losing favour among the devel-
oper community. The irony here is that AngularJS is maintained by Google.
Vue.js has been successful in adopting many of the best features of
AngularJS as well as React, which is another popular framework. The end
result is that Vue.js is one of the fastest frameworks for web development
at the moment. And which is why we’re bringing this two-part FastTrack
to Vue.js. In this first book, we’ll be focusing on the basic aspects and the
syntax for most of the unique modules and directives within Vue.js. In the
next book, we’ll focus on a few additional concepts before delving into an
actual project built using Vue.js.
We hope that this FastTrack will serve as a stepping stone in your web
development journey. Like always, we’re open to feedback and suggestions
for future FastTracks. Please write to us via editor@digit.in and we’ll be
listening. It’s now time for you to get cracking!
6 Chapter #01
Things to know about Vue.js

Copyright attribution: blog.jscrambler.com


Things to know
about Vue.js
Vue.js is one of the popular javascript
frameworks that help in website
development.

Introduction:
Technology is growing and evolving frequently. This growth is making
task execution convenient and quicker. As for front-end developers, there
are already many technologies, frameworks and helping guides available
in the market. For developing a website, numerous elements have to be kept
in mind so that the website turns out to be precisely the way a person needs.
Moreover, with so many different businesses, the number of websites also
differ. For example, an e-commerce website needs another framework than
that of a digital marketing service provider’s website.
So, every developer needs to choose the appropriate technology for
designing and developing the website. Java is one of the most used and
probably full-fledged systems on its own. But when talking about its eco-
Things to know about Vue.js 7

system, there are many things in Java apart from the language itself. Several
tools, including frameworks, make website development an easy task and
smoothens the entire development process. There are several frameworks
available in the market. Still, in the previous few years, the demand, likings
and usage have determined a significant growth of developer’s inclination
towards the Vue.js framework.

What is Vue.js?
Vue.js is an excellent Java framework invented in 2013, but it was officially
released in 2014. It is a progressive framework for user interface building
whose core functionalities work around the layers, helping the developers
integrate anything in the existing projects easily. All of this is done with
the help of extensive library support and various modern tools that are
available in the framework. With all the offerings and supporting tools
available in Vue, this framework can power several advanced applications.
According to the State of JS survey, Vue.js is one of the top three front-end
frameworks. This framework is built on a one-page application and web

Copyright Attribution: www.altexsoft.com

Use it on both desktops and mobile both


8 Things to know about Vue.js

interface. With the help of the Electron framework, Vue is used for mobile
applications and desktops.
Compared to all its competitors, Vue.js has many customised tools,
resources, and documents to help develop a website even better and quicker.
But before someone starts working on this framework, they need to get
acquainted with all the essential aspects available here. Apart from all the
other elements, getting familiar with the ecosystem is most important. Ini-
tially, a developer needs to understand this framework’s tools: its forums,
framework, and resources. Developers can also quickly install third-party
plug-ins and libraries. It also offers various browser tools that aid develop-
ment and help with debugging.

What are its competitors - Angular, React, Nuxt ... ?


There are so many competitors of Vue, and the one that comes closest to it
is Angular. Let’s check all the advantages and strengths of these competi-
tors over Vue, one by one.

React
React is known to be one of the strongest competitors of Vue as they have
a lot of things in common. Few of many similarities between React and
Vue.js include:
• These frameworks use a virtual DOM during the render process.
• They provide composable and reactive view components.
• And they maintain high focus in their core libraries.
These are some similarities that both these frameworks share, but on the
other hand, there can be a bit of deviation when it comes to performance.
Let’s check that out.

• Runtime Performance
When discussing Vue and React, their runtime performance cannot be a
decisive factor because both these frameworks showcase fast and exceptional
speed due to the virtual DOM making them equal in this arena.

• CSS and HTML


In React framework, you find nothing but only JavaScript, whereas all the
HTML structures are also expressed with the help of JSX, and recent trends
also show that CSS management is being handled inside the JavaScript itself.
Although several related benefits come with this feature, people using the
Things to know about Vue.js 9

React framework have to make a trade-off. Vue never lets any developer
feel like they are trading-off features as it has embraced all the classic web
technologies and used them to build better things.

Angular
There are many syntaxes of Vue that would look similar to that of Angular.
This is because Vue got its inspiration from Angular. There are many great
features, tools, and libraries in Angular, but it had a few drawbacks. It can
be said that Vue figured them all out and bridged the gaps before Angular
could. Here is how both these frameworks match up to each other:

• Complex
One of the downsides of Angular is the complexity it holds. Be it the design,
APIs, libraries, rendering or unzipping the framework, Vue is highly rec-
ommended due to its simplicity.

• Flexible and modular


Angular has a solid and rigid guidelines about its applications and structure,
whereas Vue is a bit more lenient and offers much more flexibility to the
user. Due to this flexibility, Vue is adaptable to a broader range of projects.

Nuxt
Nuxt is a high-level framework that needs a lot of understanding, unlike
Vue. Though it is built on top of Vue its complexity is the reason why it
takes a hit. Nuxt is a framework that extracts all the information from
client code and server.

What were the reasons for which Vue.js was developed?


The main reasons are:
• It offers a wide range of tools, library and other options.
• It has a compact size which makes downloading and unpacking easier.
• It has an exceptional rendering speed and high performance.
• It also supports two-way data distribution that is essentially helpful for
those who work on this.

Key features of Vue.js


Every technology that’s developed and introduced in the market is done for
one sole reason, to bridge the gaps. Vue.js; though this is not a new tech-
10 Things to know about Vue.js

nology, this is surely the future and better way to do your website designing
tasks. But its close resemblance to the Angular framework has already
got Vue a lot of controversies. Even though things have been a bit adverse,
front-end developers have actively chosen this framework over others in
the past few years. Several key features help Vue to best its competition.
Here are a few key reasons:

• Compact size
When you get a package that requires less time for unpacking and is quick to
install, it will always interest people. With all its libraries and tools, the entire
framework weighs only about 18 kb. It highly impacts your UX and SEO.

• Performance and Rendering


Vue.js works on the Document Object Model (DOM) that is usually encoun-
tered whenever a developer renders any web page. The DocumentObject
Model is nothing else but a representation of HTML pages with all its
elements, styles, fonts, objects and other content. In this, the browser of
the page generates a tree structure when a page is loaded, making it easier
for the website developer to understand, improvise and include essential
elements right from the first step.

Document

Root element:
(html>

Element: Element:
(head> (body>
Copyright Attribution: www.altexsoft.com

Element: Attribute: Element: Element:


(title> “href” (a> (h1>

Text: Text: Text:


“My title” “My link” “My header”

Helps in rendering the web-pages is easier with DOM


Things to know about Vue.js 11

Whenever someone lands on a web page and interacts with the page, the
elements on the landing page tend to change their state, giving the browser
a chance to update all the information. This process of updating is called
real-time rendering. Rendering the entire DOM structure is cumbersome,
hectic, and difficult on any platform. This is where Vue.js comes in handy
as it uses the virtual DOM to make things better. This virtual DOM lets the
developer render the pages without taking a hit on the speed. Let’s under-
stand this better; take the rendering process as a copy of the original DOM
that is created when a person arrives on a website page. It enables the user
to update the needful elements without affecting the other elements. This
is a phenomenal gap bridged and a great way to render the page to improve
the application’s performance.

• Two-way data binding


Two-way data binding is nothing else but a connection between the view
user interface and the data updates of any model. Each framework has a
bound component involved in it. And this element contains data that gets
updated from time to time. With the help of this data binding process, it is
not just easy to update the data but also to keep track of the changes and
the updates. Unlike Angular, the DOM objects are regularly updated in the
Vue framework, and so they are data bound. These things are an essential
part of the designing world. With both of this information available, it
makes things excellent for the application that needs real-time updates to
function correctly.

Conclusion
With all these things discussed, we can now say that Vue is a fast, simple,
and effective framework with all the essential elements that the other
frameworks lack. All the available elements with Vue can help create user
interface dynamic, making it a great way of leveraging component-based
applications. Vue also allows the integration of many features into the
building process, making it a straightforward process.
Keeping in mind the use and how it is better than its competitors, we
can say that Vue.js has a long future that developers can look forward to.
12 Vue.js installation Chapter #02

Copyright Attribution: freecodecamp.org


Vue.js
installation
Getting started with Vue.js

B
efore installing any new package, you need to follow several codes
and commands. To execute the npm (Node Package Manager)
and install Vue.js, you need to have administrator rights. You can
install it on your system only when you have the version manager
privileges from Node.js.
One of the leading frameworks, Vue.js makes it easier for the developer
to work with the user interface layer.
The design of the build is incrementally adoptable. Thus, you can weave
it easily into your project according to its requirements.
Basically, there are four ways in which you can add Vue.js:
1. Have it imported on the system as a CDN package
2. Host the downloaded JavaScript files.
3. Use npm (Node Package Manager) to install it.
4. Scaffold the project using the official CLI (Command Line Interface).
Vue.js installation 13

With Vue.js, it is easier to integrate it with other extensions and libraries.


Moreover, it is well-supported by Safari, IE, Firefox, and Chrome.

Compatibility Note
There is no support from Vue for IE8 and below. It is un-shimmable in
Internet Explorer 8 as it uses features of ECMAScript 5. Nevertheless, it
allows all browsers compliant with ECMAScript 5.

Semantic Versioning
For documented behaviour and features of all official projects, Vue follows
semantic versioning. The exposed internals or undocumented behaviour
are explained in the release notes.

Release Notes
Current stable version is 2.6.12. You can refer to the release notes of its
previous versions on GitHub.

Copyright Attribution: www.freepik.com

Vue.js installation

Vue Devtools
It is recommended to use Vue Devtools in the browser while using Vue. It
helps you to check and debug the applications. The easy interface makes
the process easier and simpler.
14 Vue.js installation

Direct <script> Include


Registered as a global variable, you can include the script tag after a
quick download.

CDN
The latest version is available to use. For learning or prototyping purposes,
you can use it with:
• <script src=”https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/
vue.js”></script>
During the production mode, it is recommended to build and link to an
appropriate version number. In addition, prevent any unexpected breakage
from the latest versions:
• <script src=”https://cdn.jsdelivr.net/npm/vue@2.6.12”></
script>
You can pick the ES Modules compatible build if you are working on
the native ES Modules:
• <script type=”module”>

Copyright Attribution: freepik.com

Installing Vue.js with CDN


Vue.js installation 15

• import Vue from ‘https://cdn.jsdelivr.net/npm/vue@2.6.12/


dist/vue.esm.browser.js’
• </script>

You can check for the NPM package source at cdn.jsdelivr.net/npm/vue.


The framework Vue is made available for the developers at cdnjs and
UNPKG. There is no latest release for cdnjs. So, it may not be fast to sync.
Look up and read about using the production version of Vue and its
different builds. You can find it in the published site where vue.min.js is
replaced with vue.js. Specifically, it is not built for development experience
but to reduce latency during the development.

NPM
If you are developing a large scale application, it is advisable to use NPM
installation method with Vue. That is because it provides optimal module
bundlers such as Browserify and Webpack. Moreover, you also get to author
Single File Components with the accompanying tools provided by Vue.
• # latest stable
• $ npm install vue

CLI
Further, the leading framework helps in enabling official CLI for quicker
complex development of Single Page Applications. It boosts setups built with
Copyright Attribution: freepik.com

Reduced Time to Market with Vue.JS


16 Vue.js installation

batteries included for a much enhanced front-end workflow. It does not take
a lot of time to get up and running, thereby increasing the Time-to-Market.
It is fast with builds ready for production, lint-on-save and hot-reload. You
can check the Vue CLI docs to know more about it.

Comparison of Different Builds


There are separate Vue.js builds in the dist/ NPM package directory. Let us
look at some of the most prominent differences between them.

UMD
Full: vue.js
Runtime-only: vue.runtime.js
Full (production): vue.min.js
Runtime-only (production): vue.runtime.min.js

CommonJS
Full: vue.common.js
Runtime-only: vue.runtime.common.js
Full (production): -
Runtime-only (production): -

ES Module (for bundlers)


Full: vue.esm.js
Runtime-only: vue.runtime.esm.js
Full (production): -
Runtime-only (production): -

ES Module (for browsers)


Full: vue.esm.browser.js
Runtime-only: -
Full (production): vue.esm.browser.min.js
Runtime-only (production): -

Terms
Here are a few terms that you may need to know before installing Vue.js.
Full: Builds that comprises both the runtime and the compiler
Compiler: Code that helps in compiling the strings of the template into the
render functions of JavaScript.
Vue.js installation 17

Runtime: Code that helps for building the instances for Vue. It also patches
and renders virtual DOM. In a nutshell, it includes everything except
the compiler.
UMD: With the help of a <script> tag, you can let the UMD builds to be
deployed directly in the browser. The Runtime and vue.js, which is the
UMD Compiler build is the standard jsDelivr CDN file that you can find
at https://cdn.jsdelivr.net/npm/vue@2.6.12.
CommonJS: These are builds that are designed to compile with older
bundlers like webpack 1 and browserify. Vue.runtime.common.js, that is
CommonJS build, stands similar to the default file for pkg.main bundlers.
ES Module: ES Modules offer two builds right from 2.6 Vue.
• ESM for browsers: The one that can be used for 2.6+ only version, the
ESM for browsers is designed to run in modern browsers for direct
imports. It can be used with <script type=”module”>
• ESM for bundlers: ESM for bundlers are used for Rollup or webpack
2 modern bundlers. The format of the ESM is planned for statistical
analysis. Thus, the bundlers can perform the “tree shaking” method and
remove the redundant set of codes from the final release. The build for
Runtime only ES Module is the default one to be taken advantage of here.

Copyright Attribution: www.freepik.com

Vue.js ESM
18 Vue.js installation

Runtime and Compiler vs. Runtime-only


You will need the full build with the compiler if you want to bundle the
templates on the client. This includes using the DOM HTML element for
its mounting in a template, passing a string to the option with the template.
• // this requires the compiler
• new Vue({
• template: ‘<div>{{ hi }}</div>’
• })

• // this does not
• new Vue({
• render (h) {
• return h(‘div’, this.hi)
• }
• })

During the build time, JavaScript compiles the files beforehand while
you use the vueify or vue-loader. You can use the compiler only in the
runtime-only build as you do not need it in the bundle for the final release.

Webpack
• module.exports = {
• // ...
• resolve: {
• alias: {
• ‘vue$’: ‘vue/dist/vue.esm.js’ // ‘vue/dist/vue.
common.js’ for webpack 1
• }
• }
• }

Rollup
• const alias = require(‘rollup-plugin-alias’)

• rollup({
• // ...
• plugins: [
• alias({
• ‘vue’: require.resolve(‘vue/dist/vue.esm.js’)
• })
Vue.js installation 19
• ]
• })

Browserify
Use the package.json for adding your projects.
• {
• // ...
• “browser”: {
• “vue”: “vue/dist/vue.common.js”
• }
• }
• Parcel
• Use package.json for adding it.
• {
• // ...
• “alias”: {
• “vue” : “./node _ modules/vue/dist/vue.common.js”
• }
• }

The difference between Development and Production Mode


The codes developed for the development and production modes of UMD
builds are very strategic and robust. Thus, you can have minified files for
production and un-minified files for development.
ES Modules and CommonJS are designed for bundlers. Thus, you would
not find its smaller or minified versions. As a result, you will have to self-
minify the final bundle.
For process.enc.NODE_ENV, ES Modules and CommonJS builds take
care of these raw checks. They help in identifying the mode that they can
be developed to run in. You need to replace the variables for the environ-
ment with proper bundler configurations. This will help in controlling the
mode of Vue. When the string literals replace process.env.NODE_ENV, they
completely reduce the use of development-only code blocks while allowing
minifiers such as UglifyJS. This influences the final file size.

Webpack
The mode option is available in Webpack 4+:
• module.exports = {
• mode: ‘production’
• }
20 Vue.js installation

However, you had to use DefinePlugin in previous versions, that is


Webpack 3 and earlier.

• var webpack = require(‘webpack’)



• module.exports = {
• // ...
• plugins: [
• // ...
• new webpack.DefinePlugin({
• ‘process.env’: {
• NODE _ ENV: JSON.stringify(‘production’)
• }
• })
• ]
• }

Rollup
Apply rollup-plugin-replace

• const replace = require(‘rollup-plugin-replace’)



• rollup({
• // ...
• plugins: [
• replace({
• ‘process.env.NODE _ ENV’: JSON.stringify(‘production’)
• })
• ]
• }).then(...)

Browserify
You can make changes to the bundle by using the global envify transform.

• NODE _ ENV=production browserify -g envify -e main.js |


uglifyjs -c -m > build.js

CSP environments
Google Chrome Apps and similar environments coerce CSP (Content Secu-
rity Policy) to prevent evaluation of expressions with new Function (). You
Vue.js installation 21

can compile templates with the full build feature. Thus, it becomes of no
use in these environments.
Contrarily, the build for runtime-only complies with the rules for CSP.
The templates will already be bundled into render functions when you are
using Browserify + vueify or Webpack + vue-loader with the runtime-only
build. It gels well with the CSP environments.

Dev Build
Github allows the checking of /dist folder only at the time of releases. You
will have to build the source code if you wish to use Vue on Github.
• git clone https://github.com/vuejs/vue.git node _ modules/
vue
• cd node _ modules/vue
• npm install
• npm run build

Bower
Bower offers only UMD builds.
• # latest stable
• $ bower install vue

AMD Module Loaders


You can directly use each UMD build as an AMD module.

Conclusion
After installing the packages, it is recommended to check for project depend-
encies and upgradation inside the project directory. The core library depends
much on the view layer only. Thus, it is able to adopt and integrate it with
existing projects and other libraries. Contrarily, it works best with decent
Single-Page Applications. All you have to do is build a strong combination
of supporting libraries and modern tooling.
The framework size of Vue.js is approximately 18 to 21 kB. Thus, you
can set it up in no time. It works seamlessly for applications that can be
run from web browsers. In addition, if you need a fast performing appli-
cation, you can rewrite it in Vue to bring its best progressive nature to its
advantage. The codebase can be introduced gradually. So, you do not have
to worry about managing it all at once. Component by component works
really well for Vue.js.
22 Vue Instance Chapter #03

Vue Instance
In contrast to other monolithic
architectures, Vue is designed from
the ground up to be incrementally
adoptable.

Introduction
Vue’s architecture was partially influenced by the MVVM pattern, despite
not being strictly affiliated with it. We sometimes use the variable VM to
attribute to our Vue instance as a convention. An options object is passed
in when you construct a Vue case. While you create a Vue instance, you
must have an options object, which can include data, prototype, element to
mount on, methods, life-cycle callbacks, and other options. While extended
instances can be created imperatively, in most cases, you would be regis-
tering a component constructor as a custom element and writing them
declaratively in templates. We’ll go into the component system in more
detail later. For the time being, all Vue.js modules are simply expanded
Vue instances.
Vue Instance 23

Data and Methods


When a Vue instance is generated, it adds to Vue’s reactivity framework all
of the properties contained in its data object. As the values of those proper-
ties change, the view “reacts,” adjusting to reflect the new values. The view
will be re-rendered if this data improves. It should be remembered that
data properties are only reactive if they were present when the instance
was formed.
It should be remembered that these proxied properties are the only ones
that are reactive. If you add a new property to an instance after it has been
developed, no view changes will be triggered. Vue instances expose various
valuable instance properties and methods in addition to data properties. To
distinguish them from proxied data objects, these properties and methods
are prefixed with $.
You may have found that the Vue components look a lot like Custom
Elements, which are part of the Web Components Spec. This is since Vue’s
component syntax is loosely based on the spec. Vue modules, for example,
incorporate the Slot API, and are a special attribute. There are, however, a
few main differences:
The Web Components Spec has been finalised, but it is not yet natively
supported by all browsers. Web elements are natively supported by Safari
10.1+, Chrome 54+, and Firefox 63+. Vue modules, on the other hand, do not
need any polyfills and run consistently across all compatible browsers (IE9
and above). Vue components can also be bundled within a native custom
product if necessary.
Copyright Attribution: Photo by Quentin Ainsworth, is
licenced under CC BY-NC-SA

Data and Methods


24 Vue Instance

Vue components provide functionality that pure custom elements do


not, most notably cross-component data flow, custom event communication,
and build tool integrations.
While Vue does not internally use custom elements, it has excellent
interoperability when consuming or delivering custom elements. Vue CLI
also allows you to create Vue components that file as native custom elements.
When a Vue instance is created, it must go through a sequence of initiali-
zation steps, such as setting up data observation, compiling the prototype,
and creating the appropriate data bindings. Along the way, it will also call
some lifecycle hooks, which will enable us to execute custom logic. Other
hooks will be named at various stages of the instance’s lifecycle, such as
compiled, primed, and demolished. Both lifecycle hooks are named with
this meaning, referring to the Vue instance that invoked it. Any users may
be asking where the definition of “controllers” exists in the universe of Vue.
js, and the response is: there are no controllers in Vue.js. Your component’s
custom logic will be distributed through these life-cycle hooks.
Another interesting principle in Vue is the component framework, an
abstraction that helps one construct large-scale applications out of light-
weight, self-contained, and mostly reusable modules. Almost any kind
of application interface can be abstracted into a tree of components if we
think about it.

CODE:
• var data = { a: 1 }

• // The object is added to a Vue instance
• var vm = new Vue({
• data: data
• })

• // Getting the property on the instance
• // returns the one from the original data
• vm.a == data.a // => true

• // Setting the property on the instance
• // also affects the original data
• vm.a = 2
• data.a // => 2

Vue Instance 25

• // ... and vice-versa


• data.a = 3
• vm.a // => 3

The root Vue instance, or Vue instance for short, is at the core of any Vue
program, large or small. Invoking the Vue constructor, new Vue creates a
root Vue case (). The constructor bootstraps our framework by compiling an
HTML blueprint for it, implementing some instance data, and generating the
data and event dependencies that make it immersive. New Vue (/* options
go here */) accepts a single JavaScript object known as the options object.
It is our responsibility to populate the object with all the Vue constructors
required to bootstrap our program. But for now, we will concentrate on a
single alternative, the el option.
Vue uses the ‘el’ alternative to designate a DOM feature where our
application will be mounted. Vue can find the corresponding DOM feature
in our HTML and use it as the app’s command prompt.
Vue.js employs an HTML-based template syntax that allows you to con-
nect the transformed DOM to the underlying Vue instance’s data declara-
tively. Both Vue.js templates are real HTML that can be interpreted by
browsers and HTML parsers that support the spec.
Vue compiles the models into Virtual DOM render functions behind the
scenes. When combined with the reactivity system, Vue can intelligently
determine the smallest number of components to re-render and the smallest
amount of DOM manipulations to add when the app state changes.

Explanation of Vue instance Lifecycle Hooks


The following is a list of all the incidents and hooks that a Vue instance goes
through. Vue has eight life-cycle methods/events or hooks.
Js Instance Life-cycle:
• Created hook- The created () hook is used to execute code after the
instance has been created. It allows you to view reactive details, but the
mounting or rendering of templates and virtual DOM has not yet been
done. Even though models have not yet been installed or made, events
are active, and access to reactive data is allowed in this hook.
• Mounted hook- The mounted () hook is the most common case or hook.
This hook gives you complete control over the reactive part, models, and
made DOM. You have complete control over the reactive component,
models, and rendered DOM in this hook.
• Before create hook- The first occurrence or hook that happens during
26 Vue Instance

the construction process is the before Create () hook. It allows developers


to execute activities until the component is to be added to the DOM. We
are unable to do anything about the DOM in this case. The data in this
hook and the incidents that happened during the component life-cycle
are not reactive.
• Updated hook- The updated () hook is called after the data on the com-
ponent changes and the DOM re-renders. It is the safest way to complete
this action if you want to reach the DOM after a property update.
• Destroyed hook- The destroyed () hook is the last stage in the Vue.js
Instance life-cycle and is used to do any final clean up.
• Before mount hook- The before Mount () hook is called only before the
original render and after the prototype or change functions that have
accumulated. It is called after Vue has compiled the blueprint and modi-
fied the virtual DOM. This is a seldom-used occurrence, and in most
situations, it is unnecessary to use it.
• Before update hook- The before Update () hook is called only before the
component’s data shifts and the upgrade period begins. It is executed
immediately before the DOM is changed and updated.
• Before destroy hook- The before Destroy () hook is called only before
the instance is destroyed. This is the second last step in the Vue Instance
life-cycle and is the appropriate place to tidy up incidents or reactive
subscriptions if necessary. Copyright Attribution: Photo by Bo Andersen, is
licenced under CC BY-NC-SA

Explanation of Vue instance Lifecycle Hooks


Vue Instance 27

As mentioned above, each Vue instance must go through a set of ini-


tialization steps. When you generate an instance, it must configure data
observation, compile the prototype, install the instance to the DOM, and
update the DOM as data changes.

Vue.js dynamic components and Vue.js computed properties.


A dynamic component is one whose position in the program is not deter-
mined at build time. It is not specified in any Vue.js template. Instead, at
runtime, the dynamic component is instantiated and added to the program.
A dynamic component in Vue.js is generated with the tags <component></
component> and bound with a property. Let’s look at a scenario to help
you understand.

Copyright Attribution: Photo by Yaron Biton, is licenced


under CC BY-NC-SA

Vue.js dynamic components and Vue.js computed properties.

Computed properties are used in Vue.js when dealing with complex


logic and operations. Computed properties are like processes, although
there are certain variations.
In previous examples, we successfully used in-template expressions.
While they are very useful, in-template expressions are still used for basic
operations. If you must use a lot of abstract logic in your models, they will
become bloated and difficult to manage.
When we type in the textbox, the feature returns the same value regard-
less of whether the property’s first name or last name changes. As a result,
we don’t have to do something special with computation, such as remem-
28 Vue Instance

bering to call a function. As the properties used within a shift, such as first
name and last name, the computed property is named by itself. We now
understand what computed properties are. Now, let’s look at the distinction
between a process and a computed property. We know that both are objects
with functions specified inside that return a value.
In the case of computed properties, we call it property, while in the case
of methods, we call it a function.
After running the file, if you change the textbox, the changed name
will be displayed in the browser. Because of the set feature, the first name
and last name are modified here. The get function returns the first and last
name, while the set function updates it if anything in the textbox is changed.
When Vue.js computed property is compared to Vue.js watch property,
the Vue.js watch property dispenses with a more generic way to monitor
and respond to data changes.
Accumulated data can be modified based on other data. Using the watch
object is simple, particularly in an AngularJS context. However, rather than
an imperative watch call back, it is preferable to use a computed object.

Vue.js Events
Events are used in Vue.js to respond to an event. If you need to create a
responsive website using Vue.js, you’ll most definitely want it to be able
to adapt to events.
For example, if your Vue.js website has clickable buttons, forms, and so
on, you would undoubtedly want your Vue.js website to react in some way
when a user clicks a button, submits a form, or even moves their mouse.
To manage an event with Vue.js, add the ‘v-on’ directive to the appropriate
DOM variable.
Aside from click, you can manage a variety of other Vue.js DOM cases.
Vue.js can manage both native web and mobile events as well as custom
events. Listed below are the most important incidents that are typically
handled:
• submit
• key up!
• drag
• scroll
• error
• abort
• mouseover
Vue Instance 29

• mouse out
• load etc.
In addition, two variables, clicknum and clicknum1, have been speci-
fied. When the button is pressed, both are increased. All variables are set
to zero. It’s seen in the output above. The vector clicknum is increased by
one as you click the first button. The number is not incremented on the
second click because the modifier forbids it from initiating or performing
any action item delegated on the click of the mouse. When you press the
second button, the same operation is performed; namely, the attribute is
incremented. The value is incremented and shown for each press.

Conclusion
We have covered the most common aspects of Vue.js core in a nutshell. The
remainder of this book will explain them and other advanced features in
greater depth, so make sure to read it all! This is just a high-level description
of Vue.js. As previously said, a Vue.js presentation may be a whole refer-
ence book in itself, but we hope this gives you a general rundown of this
enjoyable and progressive platform. If you’re a seasoned Vue.js developer
or this is an introduction, Vue.js and its community has a lot to offer. You
can now be more prepared to investigate other platforms and frameworks,
such as VuePress, NativeScript for Vue, and Nuxt.js.
30 Template Syntax Chapter #04

Template
Syntax
Vue.js is quite different from the way
typical frameworks are invoked.
Template Syntax 31

V
ue-js is one of the most predominantly used frameworks in recent
times. It is used to build single-page applications and user inter-
faces. Its reactivity and simplicity are extremely impressive. It
collates the best features of two JavaScript frameworks, React
and Angular. As it offers a neutral environment, most of the developers
like to use Vue.js.
With the Electron framework, Vue.js is also used for both mobile and
desktop app development. The JS base and HTML extension played in favor
of this front-end tool, resulting in giants such as Xiaomi, Gitlab, Alibaba,
Behance, and Adobe adopting it.
Based on HTML-based template syntax, Vue.js enables the developer
to compile the rendered DOM to the instance’s data that is underlying the
Vue. Each Vue.js is valid HTML that can be parsed by HTML parsers and
spec-compliant browsers.
Technically, Vue binds the Virtual DOM to render functions with the
templates. That means the templates of Vue.js are essentially enhanced
with parsable HTML and are valid with a few special attributes. During the
combination with the reactivity system, Vue can identify the least number
of components to re-render and use the fewest number of DOM manipula-
tions after the state of the app changes.

Comparison
Let us quickly look at Vue’s template when compared to a JavaScript DOM
manipulation that does not include Vue. In the following example, we are
using a provided div to insert text.
• // jQuery
• const divElement = $(‘#text’);
• divElement.text(‘Hello Vue’)

It is not simple with JavaScript.


• // JavaScript
• const divElement = document.getElementById(‘text’);
• const textNode = document.createTextNode(‘Hello Vue’);
• divElement.appendChild(textNode);

However, with Vue, it is very much declarative and simple.


• new Vue({
• template: `<div>{{text}}</div>`,
32 Template Syntax

• data () {
• return {
• text: ‘Hello Vue’
• };
• }
• }).$mount(‘#app’)

The data (model) and template (view) are divided into different segments
but collated together with the help of object properties.
Let us know more about the binding concept.

Interpolations
• Text
Text interpolation is the root form of data binding. You can build it using
double curly braces, also known as the “Mustache” syntax. Vue is not the
only program that uses these curly brackets.
• <div> Product: {{product}} </div>
The product property value replaces the double curly brackets on the
corresponding data object. When there is a change in the product property
of the data object, the values will be updated.
You can perform one-time interpolations with the help of the v-once
directive. These do not re-render when there is a change in data. Never-
theless, this can influence the other bindings which are available on the
same node.
• <div v-once> this will never change: {{product}} </div>

• Raw HTML
The double curly brackets always interpret the data as plain text and not
as HTML. Use the v-html directive to have a real HTML as the output.
• <p>Using mustaches: {{ rawHtml }}</p>
• <p>Using v-html directive: <span v-html=”rawHtml”></
span></p>
Along with the product property value, the span contents re-renders,
ignoring the data bindings and interpreting as plain HTML. Vue does not
belong to the templating engine based on strings. Hence, you cannot com-
pose template partials using v-html.
Your website can be prone to XSS attacks with dynamically rendering
arbitrary HTML. Thus, it is advisable to never use HTML interpolation on
user-provided content but trusted content.
Template Syntax 33

Attributes
The v-bind directive can replace the HTML attributes.
• <div v-bind:id=”dynamicId”></div>
For boolean attributes, v-bind does not work the same where the mere
existence implies true. For example:
• <button v-bind:disabled=”disabled”>Button</button>
If the value for disabled is false, undefined or null, the <button> element
will not be rendered and include the disabled attribute.

Using JavaScript Expressions


The text that we put in the curly brackets is known as binding expressions.
A binding expression, in Vue.js, comprises a standalone JavaScript expres-
sion followed by one or more filters.
In our templates, we usually bind simple property keys. However, vue.js
supports all data bindings lying inside to the best of JavaScript expressions.
• {{ value + 1 }}
• {{satisfied ? ‘YES’ : ‘NO’ }}
• {{sentence.split(‘’).reverse().join(‘’)}}
• <ul v-bind:id=”’product-’+id”></ul>

These expressions will be checked as JavaScript while deciding the data


scope of the owner Vue instance. But it is worth noting that this binding
cannot have more than one single expression. It will not work if there is
more than one expression.

Filters
In Vue.js, you can use filters at the end of the expression. It is marked as the
“pipe” symbol. Here is an example:
• {{ message | capitalize }}
The pipe symbol means we are piping the message expression value
with the help of a built-in “capitalize” filter. However, do not include the
pipe syntax inside the expressions. They are only to be used outside and
not make it a part of the JavaScript expression.

Directives
The special attributes that come with the v- prefix, directives, and directive
attribute values are usually considered to render as a single JavaScript
expression. There is just one exception, and that is for v-for. Whenever there
is a change in expression values, you can apply side effects to Document
34 Template Syntax

Object Model reactively with the help of DOM.


• <p v-if=”seen”>Now you see me</p>
In this example, based on the truthfulness of the seen expression value,
the v-if directive can change the <div> element. It can either remove the
element or get it inserted.

Arguments
Some directives may take the form of an argument in Vue. You can use
it after the directive name is denoted by a colon. Here is an example that
depicts the v-bind directive:
• <a v-bind:href=”url”> ... </a>
In this example, v-bind is the directive and href is the argument. Href
directs the directive to bind the href attributes to the expression value of
the url.
Let’s look at another example with a v-on directive. This follows the
DOM events:
• <a v-on:click=”doSomething”> ... </a>
Here, the value of the eventName is “focus,” there will be an equivalency
between v-on:[eventName] and v-on:focus.

Dynamic Argument Value Constraints


The one that evaluates to a string, dynamic arguments puts forth the null
exception. You can explicitly remove the binding with the special value null.
It will throw a warning if there is any other non-string value.

Dynamic Argument Expression Constraints


There are some limitations with respect to the syntax for dynamic argument
expressions. A few characters, such as quotes and spaces, do not stand valid
while using the HTML attribute names. For example, the following can be
considered as null and void:
• <!-- This will trigger a compiler warning. -->
• <a v-bind:[‘foo’ + bar]=”value”> ... </a>

You can either replace the complex expression or use it without quotes
or spaces with a computed property.
When you are picking the templates which are directly written in the
HTML file like the in-DOM templates, it is best to prevent using uppercase
characters, including naming keys as browsers will convert these attribute
names into lowercase:
Template Syntax 35

• <!--
• This will be converted to v-bind:[someattr] in in-DOM
templates.
• Unless you have a “someattr” property in your instance,
your code won’t work.
• -->
• <a v-bind:[someAttr]=”value”> ... </a>

Modifiers
Vue uses the Modifiers to change some of the attributes’ behaviours inside
the template. Represented by a dot, modifiers are special postfixes. They
state that there is a special way for every directive to bind.
For example, the event.preventDefault() can be called upon when the
.prevent modifier notifies the directive on the triggered event:
• <form v-on:submit.prevent=”onSubmit”> ... </form>

Shorthands
Shorthands can be used the most when you feel the template takes a lot of
keystrokes. The v- prefix defines the template with a visual cue for picking
only specific attributes of the Vue. If you are using Vue.js, this will be useful
when you want to patch dynamic behaviour with the given markup. How-
ever, the template may be filled with a lot of text with the use of directives.
Likewise, there is no much need to implement the v- prefix while com-
posing a SPA. In SPA, every template is managed by Vue. Hence, Vue is
known to offer special shorthands to two of the most prevailing directives,
v-on and v-bind.

• v-on Shorthand
• <!-- full syntax -->
• <a v-on:click=”doSomething”> ... </a>

• <!-- shorthand -->
• <a @click=”doSomething”> ... </a>

• <!-- shorthand with dynamic argument (2.6.0+) -->
• <a @[event]=”doSomething”> ... </a>

• v-bind Shorthand
• <!-- full syntax -->
36 Template Syntax
• <a v-bind:href=”url”> ... </a>

• <!-- shorthand -->
• <a :href=”url”> ... </a>

• <!-- shorthand with dynamic argument (2.6.0+) -->
• <a :[key]=”url”> ... </a>
Normal HTML may not look similar to this. But, the @ and : can be
perfectly parsed by all Vue-supported browsers, and thus, they are valid
characters that go well for the attribute names. Furthermore, there is no
trace of these characters in the final rendered markup. This is not an optional
shorthand syntax. Nevertheless, you would like to make maximum usage
of this template when you learn more about it.

Conclusion
Vue.js was at first developed for prototyping. It is one of the most amazing
tools to handle graphics, interactive elements, and a lot of animations with
proper data-binding. On the other hand, it only requires JS, CSS, and HTML.
So, there are no acute things specific to Vue. With JavaScript, it can be easily
molded into any other project that involves JS. It is compatible with several
frameworks and technologies such as Django, Rails, Express, and Laravel.
The components in Vue are identified as encapsulated elements for
the interface. You can write these in JavaScript, CSS, and HTML without
distributing them into separate files. Such splitting of files can be best used
for unit-testing, code readability, and component reusability.
Being a leading framework in the industry for more than 5 years, it has
gained a lot of prominence for its compatibility with various other sets of
tools. Its adoption is easy to understand. With Vue, you do not need an in-
depth knowledge of TypeScript, JSX, or libraries. All you need is to know
JavaScript, CSS, and HTML. The framework is featherweight. Thus, it does
not take much time to download and install the library. This greatly influ-
ences the UX and SEO of your webpage.
Chapter #05Computed Properties 37

Computed
Properties
Why are computed properties the best
for implementing complex logic, and
how can it be done?

C
omputed properties are used to perform the quick calculations
displayed in the view. These calculations are cached and only
updated when needed. There exist several ways in Vue where
the set of values are viewed. This further lets you view the data
value, using simple expressions and filters to perform simple transforma-
tions for the content being uploaded. Also, computed properties are used
to display the value based on a particular value being fed into the structure
or the set of values modeled.

Computed Properties
Computed properties allow an operator to have model-specific data and
the complex values computed for the view. These values are bound to the
38 Computed Properties

dependency values and updated only when required. The computed proper-
ties are a great mechanism to summarize the reactive logic and implement
the consistent values or auto-update UIs.
In the past few years, there seems to be an increasing tendency of max-
imising the use of template helpers as the main tool to express the logic
right in the templates. In this, you will learn about the best choices and the
drawbacks. Let’s begin.
Computed properties pave the way for defining the properties as the
justification or function of other properties. You need to re-evaluate the
properties automatically when computer properties depend on the change
so that they don’t get out of sync. It is one of the progressive frameworks.
These frameworks are used to build the user interface. It consists of an
approachable core of the library. It is focused on the view layer only and
the ecosystem that uses a supporting library to help the operator tackle
complexity. Some properties calculate the values rather than store them.
In other words, no general or actual memory is stored for them. Instead,
they are calculated on the fly each time the operator accesses them. These
are called computed properties.
In this article, you will learn about the different kinds of properties. You
will learn some tricks used for working with the properties. For example,

Copyright: Photo by Manning Publications is licensed under CC BY-NC-SA

Update events with computed properties


Computed Properties 39

how to monitor the changes in a property or its value and delay the initiali-
zation of stored property.
Computed properties work like methods. The difference lies in the
re-run when one of the dependencies changes. In an example given below,
the system will re-run when the array ToDoItems change.
To create a computed property, there would be a need to add a “com-
puted” property to the component object, much like what is used in the
“method” process.
• <h2>{{ToDoItems.filter(item => item.done).length}} out of
{{ToDoItems.length}} items completed</h2>

Here, we have two items completed out of a total of five items on our
to-do list. Our summary could read as “two items completed out of five”.
Add the code to your app component object in the methods property.
The list of the summary methods will get the number of the ToDoItems and
return to the string reporting to this:
• computed: {
• listSummary() {
• const numberFinishedItems = this.ToDoItems.
filter(item =>item.done).length
• return `${numberFinishedItems} out of ${this.
ToDoItems.length} items completed`
• }
• }

Now you can add - {{listSummary}} directly to your template. This will
be added inside an <h2> element, above the elements written above <ul>.
Now add an id and an aria-labelledby to assign the <h2> contents for the
label of the element in <ul>

Now add the described <h2> and then update <ul> in the interior of your
app’s template. The template will now read like this:
• <h2 id=”list-summary”>{{listSummary}}</h2>
• <ul aria-labelledby=”list-summary” class=”stack-large”>
• <li v-for=”item in ToDoItems” :key=”item.id”>
• <to-do-item :label=”item.label” :done=”item.done”
:id=”item.id”></to-do-item>
• </li>
• </ul>
40 Computed Properties

Now, watch the list summary in your app. See the total number of items
being updated. Nowadays, we do not check the “done” data in any situa-
tion. However, if you are trying to check or uncheck the items, you will
identify a bug.

• Now tracking the changes and approaching to be “done.”


You can capture the checkbox and update or manage the checklist accord-
ingly. To trigger the change, attach @change to each check box instead of
using a v-model.
Now, update the element and add:
• <input> in ToDoItem.vue

Since the checkbox was checked and we need to emit it, you can include
in the line:
• $emit()
• <input type=”checkbox” class=”checkbox” :id=”id”
:checked=”isDone”
• @change=”$emit(‘checkbox-changed’)” />

Now, add a new method called updateDoneStatus() in the App.vue


below addToDo(). This would take one parameter, i.e., todo item id. Now,
we want to find the item and match the id and update it to be “done” as of
its current status.
Now, add a new method below your method. This method should take
one parameter: the todo item id. We want to find the item with the matching
id and update its done status as the opposite of its current status.
Now, we want to run the method with ToDoItem to emit a checkbox- to
change the event and pass in its item.id as the parameter. Now, update your
<to-do-item></to-do-item> that will be seen as:
• updateDoneStatus(toDoId) {
• const toDoToUpdate = this.ToDoItems.find(item => item.id
=== toDoId)
• toDoToUpdate.done = !toDoToUpdate.done
• }
• <to-do-item :label=”item.label” :done=”item.done”
:id=”item.id”
• @checkbox-changed=”updateDoneStatus(item.
id)”>
• </to-do-item>
Computed Properties 41

• In Vue.js you can output any data value using parentheses


• <template>
• <p>{{ count }}</p>
• </template>

• <script>
• export default {
• data() {
• return {
• count: 1
• }
• }
• }
• </script>
This one property can host some small computations like:
• <template>
• {{ count * 10 }}
• </template>

But in computed properties, you remain limited to the single


Javascript expression.
In addition to this limitation, it should be noted that templates should
be concerned with data being displayed to the user instead of performing
logic computations.
To have declarative templates and do something more with the single
expression, you use computed properties.
Computed properties are defined in the Vue component.
• <script>
• export default {
• computed: {

• }
• }
• </script>

• Example of Computed Property


In the example code of the computed property, use count to calculate the
output. Here:
1. You don’t need to call count () as Vue.js automatically calls on the function.
2. You can use a regular function like the one used here (if not an array
42 Computed Properties

Copyright: Photo by anonymous is licensed under


CC BY-NC-SA
View Model

function) to define the count as the computed property. This is because


we will be able to access the component.
• <template>
• <p>{{ count }}</p>
• </template>

• <script>
• export default {
• data() {
• return {
• items: [1, 2, 3]
• }
• },
• computed: {


• count: function() {
• return ‘The count is ‘ + this.items.length * 10
• }
• }
• }
• </script>

• Computed Properties are cached


If you are familiar with Vue methods, you will be amazed to know the dif-
Computed Properties 43

ference. First, in the method, you need to call count () instead of computed,
if you have a count () method. The main difference between the computed
properties and the methods is that computed properties are cached.
• <script>
• export default {
• data() {
• return {
• items: [1, 2, 3]
• }
• },
• methods: {
• count: function() {
• return ‘The count is ‘ + this.items.length * 10
• }
• }
• }
• </script>

The result of the count is internally cached. It will be cached until the
data items property changes.
It should be noted that computed properties are updated only when
reactive source updates. Regular Javascript methods are not reactive. Hence,
one of the common examples to use is with Date.now ()

Copyright: Photo by Hassan Djirdeh is licensed under CC BY-NC-SA

Methods and Computed Properties


44 Computed Properties
• <template>
• <p>{{ now }}</p>
• </template>

• <script>
• export default {
• computed: {
• now: function () {
• return Date.now()
• }
• }
• }
• </script>

It will render once but will not re-render or will not even update. Refresh
just on the page when the Vue component is reinitialized.

• The online expressions involving Vue.js’ are more convenient.


Vue.js’ inline expressions are very convenient. You should use computed
properties for more complicated logic. A computed property is used to
describe a declarative value that further depends on other values. When you
do data- bind to a computed property within the template, Vue knows when
it is rendered to be updated where any of the values depending upon the
computed properties have been changed. This turns out to be very powerful.
The codes are more declarative, easier, and data-driven. Often, it is a better
idea to use computed properties instead of imperative $watch callback.
• var vm = new Vue({
• data: {
• firstName: ‘Foo’,
• lastName: ‘Bar’,
• fullName: ‘Foo Bar’
• }
• })

• vm.$watch(‘firstName’, function (val) {
• this.fullName = val + ‘ ‘ + this.lastName
• })

• vm.$watch(‘lastName’, function (val) {
• this.fullName = this.firstName + ‘ ‘ + val
• })
Computed Properties 45

Consider this example in computed property:


• // ...
• computed: {
• fullName: {
• // getter
• get: function () {
• return this.firstName + ‘ ‘ + this.lastName
• },
• // setter
• set: function (newValue) {
• var names = newValue.split(‘ ‘)
• this.firstName = names[0]
• this.lastName = names[names.length - 1]
• }
• }
• }
• // ...
Computed properties just behave like getters. Whenever you access
it, the getter function re-evaluates. Computed properties are cached only
when one of its reactive dependencies has been changed.
Let’s take an example. Suppose you have an expensive computed
property named A. It will require looping through an array, and a lot of
computation will be involved. Now, we have another computed property
dependent on A. If it is not cached, we will call it getter many more times
than required. This would potentially cause issues with performance. If
it is cached, its dependencies will not be changed, and you can access it
many times that will further not trigger any unnecessary computations.
Furthermore, it is very important to understand what ‘reactive depend-
ency’ means.
• var vm = new Vue({
• data: {
• msg: ‘hi’
• },
• computed: {
• example: function () {
• return Date.now() + this.msg
• }
• }
• })
46 Computed Properties

In this example, the computed property relies on vm.msg. This is because


it is an observed data property in Vue. It is considered to be reactive depend-
ence. Here, it is to be noted that whenever vm.msg changes, vm.example
value would be re-evaluated.
Here, Date.now() is not a reactive dependency. This is because it has
nothing to do with Vue and its data observation system. Therefore, when
you access the vm.example, you will find the time stamp to be the same. It
will remain the same until vm.msg is re-evaluated.
Sometimes, it becomes necessary to getter, where you go to access every
time and access for vm.example. It would simply re-evaluate. Thereby,
starting in 0.12.11, it would be possible to turn off caching for the particular
case of computed property.

• computed: {
• example: {
• cache: false,
• get: function () {
• return Date.now() + this.msg
• }
• }
• }

Now, when you have access to vm.example, the time stamp would be up-
to-date. This would only affect the programme access and inside of the Java
Script and data binding that would still be dependency-driven. Whenever
you bind to the computed property in the template with {{example}}, the
DOM would be updated when the reactive dependency changes.
• <div id=”example”>
• <p>Original message: “{{ message }}”</p>
• <p>Computed reversed message: “{{ reversedMessage }}”</
p>
• </div>
• var vm = new Vue({
• el: ‘#example’,
• data: {
• message: ‘Hello’
• },
• computed: {
• // a computed getter
• reversedMessage: function () {
Computed Properties 47
• // `this` points to the vm instance


• return this.message.split(‘’).reverse().join(‘’)
• }
• }
• })
Result:
Original message: “Hello”
Computed Reverse Message: “olleH”
Here, computed property has been declared with “reversed message”.
The function is used as a getter function for the property.
• console.log(vm.reversedMessage) // => ‘olleH’
• vm.message = ‘Goodbye’
• console.log(vm.reversedMessage) // => ‘eybdooG’

Here, you can open the console and conduct your own example with vm.
The value of vm.reversed message is dependent on the value of vm.message.
Just like a normal property, you can data bind with computed prop-
erty in the given template. In this, vm.reversedMessage depends on
vm.message, so it would automatically update the binding that depends
on vm.reversedMessage whenever vm.message changes.
Here, the best part is that a declarative relationship has been created with
this dependency. Also, the computed getter function has no side effects. In
fact, it is much easier to understand and test simultaneously.

Computed Property vs. Method


It should be noted that here we can stimulate the same result with the fol-
lowing codes:
• <p>Reversed message: “{{ reverseMessage() }}”</p>
• // in component
• methods: {
• reverseMessage: function () {
• return this.message.split(‘’).reverse().join(‘’)
• }
• }

In the same way, we can define a method. Both would approach the same
results. However, again the difference is that the computed properties are
cached and have reactive dependencies. A computed property would only
re-evaluate when any of its reactive dependencies change. This means
48 Computed Properties

that the message will not change, and the multiple accesses to the message
reversedMessage will immediately result in the previously computed
results without running on the function again.
• computed: {
• now: function () {
• return Date.now()
• }
• }

Why is Caching Required?


Let us assume that we have an expensive computed property signed by A.
This would require looping through a huge array and a lot of computations.
We would then have another computed property that would further depend
on A. Without caching, we would be executing getters of A as many times
as required. In cases where no caching is needed, we can use the method.

Computed Property vs. Watched Property


Vue provides a generic way to react to the data changes. For example, when
you have some data required to be changed to some other data, it would
be tempting to overuse watch, especially when you are coming from an
AngularJS background. Moreover, it is often a better idea to utilize computed
property rather than using an imperative watch callback.
Copyright: Photo by Ben Morrow is licensed under CC BY-NC-SA

Value getter as a method or computed property


Computed Properties 49

Let us again consider this example:


• <div id=”demo”>{{ fullName }}</div>
• var vm = new Vue({
• el: ‘#demo’,
• data: {
• firstName: ‘Foo’,
• lastName: ‘Bar’,
• fullName: ‘Foo Bar’
• },
• watch: {
• firstName: function (val) {
• this.fullName = val + ‘ ‘ + this.lastName
• },
• lastName: function (val) {
• this.fullName = this.firstName + ‘ ‘ + val
• } } })
The above code is repetitive and imperative. You can compare it with a
computed property version:
• var vm = new Vue({
• el: ‘#demo’,
• data: {
• firstName: ‘Foo’,
• lastName: ‘Bar’
• },
• computed: {
• fullName: function () {
• return this.firstName + ‘ ‘ + this.lastName
• } } })

• Computed Setter
Computed properties use default getter-only, but you can also provide it
a setter when required:
• // ...
• computed: {
• fullName: {
• // getter
• get: function () {
• return this.firstName + ‘ ‘ + this.lastName
• },
• // setter
50 Computed Properties
• set: function (newValue) {
• var names = newValue.split(‘ ‘)
• this.firstName = names[0]
• this.lastName = names[names.length - 1]
• } } }
• // ...

• Watchers
Although computed properties are more appropriate, there are times when
you may require a custom watcher. This is why Vue provides a more inclu-
sive way to react to data changes through the option “watch”. This is, in
turn, more useful when needed to perform asynchronous or expensive
operations. For Example:
• <div id=”watch-example”>
• <p>
• Ask a yes/no question:
• <input v-model=”question”>
• </p>
• <p>{{ answer }}</p>
• </div>

In this case, the watch option would allow us to perform an asynchro-


nous operation that would limit how often we perform that operation and
set intermediary states until we reach a final answer. None of that would be
possible with a computed property. In addition, you can also use vm.$watch
API instead of the watch option.

Conclusion
Computed properties are defined by stored properties, classes, structure,
and enumerations, which do not allow storing a value. Instead of this, they
provide a getter that further sets properties and values indirectly.
Computed properties are used to handle complex logic and opera-
tions. These are just like methods but have certain differences that make
them convenient and useful for simple operations. The primary difference
between methods and computed property is that we refer to it as property
when talking about computed properties. In contrast, we call it a function
in the case of methods. The in-template expressions are used for simple
operations, as putting a lot of pressure, and heavy and complex logic in the
templates make it difficult to maintain.
Chapter #06
Class and Style Bindings 51

Reactgo
Class and Style
Bindings
When modifying an element’s class
list and inline styles, data-binding
is required.

Introduction
Data binding is often used to manipulate an element’s class list and inline
styles. Due to the fact that they are both attributes, we can manage them
using v-bind: we just need to evaluate a final string using our expressions.
However, tinkering with string concatenation is inconvenient and vulnerable
to error. As a result, Vue offers additional benefits when v-bind is used in
conjunction with class and style. Along with lists, expressions will evaluate
to objects and arrays.
Vue.js is a framework for developing User Interfaces (UIs) and Single-
Page Applications (SPAs) (SPAs). It’s simple to understand how to use Vue.
js and the framework of liberty and convenience that comes with it while
designing software in this program, since it combines the best aspects of
52 Class and Style Bindings

Angular and ReactJS. As a result, it is well-known for its simple-to-use


and tidy coding.
Vue.js has style linking, which enables dynamic style changes. In any
HTML tag, you can add a variable to the style attribute and have the style
shift as the binding variable changes. We’ll look at how to use style binding
and change the formatting of variables in vue.js.

Classes: Static and Dynamic


In Vue, modules can include both static and dynamic classes.
Static classes are those that never shift and are still present on the com-
ponent. On the other side, dynamic classes are those that enable one to add
and delete items as our program changes.
If we were to include a static class, we would do it exactly like we would
in standard HTML:

Copyright Attribution:
Michaelnthiessen
Including static class

Dynamic classes are very close to static classes, but we must use Vue’s
unique property syntax, v-bind, to associate a Javascript expression with
our class:
Copyright Attribution:
Michaelnthiessen

JavaScript expression for v-bind

You’ll find that we had to use additional quotes around the name of our
complex class.
This is because the v-bind syntax accepts whatever Javascript value we
transfer. By using the quotations, you ensure that Vue treats it as a string.
Additionally, Vue has a shortcut syntax for v-bind:
Class and Style Bindings 53

Copyright Attribution:
Michaelnthiessen
shortcut syntex for v-bind

What’s really cool is that you can also provide a component of both static
and dynamic classes.
This enables you to provide static classes for items that are certain to
remain constant, such as positioning and structure, and dynamic classes
for your theme:

Copyright Attribution: Michaelnthiessen

Classname applied

In this instance, theme refers to the variable containing the classname


to be applied (remember, it’s treating it as Javascript in that case).
54 Class and Style Bindings

Binding in the Vue Style


Vue.js’s v-bind:style and v-bind:class directives allow dynamically binding
styles and classes to elements.
Consider the following scenario: we want to dynamically change the
font size or margin of some feature depending on user feedback. With
v-bind:type, Vue offers interactive style binding. Consider the following
data model as an illustration.

Copyright Attribution: Mirimad


Dynamically changing margin

Let’s build a sample with two buttons and an inline expression that
increments and decrements the margin variable on the click event:

Copyright Attribution: Mirimad

Building a sample

Following the keys, we have a paragraph with a v-bind:style tag. This


assigns the value of the margin variable to the CSS margin property.
Note : camelCase would be converted to dash-case syntax in this case
(ie: fontSize to font-size).
Rather than include all styles in the inline expression, we should hold
Class and Style Bindings 55

a style object in the model and use it in conjunction with the v-bind:style
directive.

Multiple styles array | Binding


If several type objects need to be added to the v-bind:style directive. We
may have the following type artifacts in the data model:

Copyright Attribution: Mirimad


multiple style array

Prefixing Automatically
Referring to cross-browser compatibility. Vue automatically adds the appro-
priate vendor prefixes to assist in maintaining a clean syntax. With prefixes
such as -moz or -webkit.

Dynamically Creating Binding Classes


Direct styles are not the safest technique, and they may become complicated
when criteria shift. To our rescue, the v-bind:class directive enables us to
associate classes with any variable.
For instance, when a todo item is chosen, the color and font-weight will
need to be changed.
Notice the same data model.
Copyright Attribution: Mirimad

Selecting font and colour


56 Class and Style Bindings

When an object is pressed, the chosen variable’s value is adjusted to


equal the value of the currently selected item. With this in effect, we may
use the v-bind:class directive to set the item’s selected class if the selected
variable is equivalent to the current item:

Copyright Attribution: Mirimad


v-bind class directive

Binding Multiple Classes


Similarly to how we implemented multiple styles using array syntax, we
may also add multiple classes to an object via the v-bind:class directive by
forwarding an array of classes.
The data model will describe the class list as follows:
Copyright Attribution: Mirimad

Multiple classes

This will add the element with both the chosen and bolder classes. When
we modify the collection in the model dynamically, the modifications are
immediately mirrored in the example.

Using v-bind to bind HTML classes and styles on a page


Syntax of Objects
To dynamically toggle classes, we may transfer an object to v-bind:class:
Class and Style Bindings 57

Attribution:
Copyright

Vuejs
isActive class

The preceding syntax indicates that the active class’s existence would
be calculated by the truthfulness of the data property isActive.
Multiple classes may be toggled by adding additional fields to the entity.
Additionally, the v-bind:class directive may live alongside the standard class
parameter. As an example, consider the following template:

Copyright Attribution:
Vuejs
Multiple classes

Additionally, the following data:

Copyright Attribution: Vuejs

Adding data

It will produce the following:


Copyright Attribu-
tion: Vuejs

Output

When isActive or hasError updates, the class list is revised to reflect


the adjustment. For instance, if hasError is set to true, the class list will be
replaced with “static active text-danger”.
58 Class and Style Bindings

It is not essential for the bound entity to be inline:

Copyright Attribution: Vuejs


hasError

This would provide the same outcome. Additionally, we can attach an


object to a computed property that returns an item. This is a frequent and
effective pattern:

Copyright Attribution: Vuejs

Effective pattern

Array Syntax
To apply a collection of classes, we may transfer an array to v-bind:class:
Class and Style Bindings 59

Copyright Attribution: Vuejs


Array

This will render:


• <div class=”active text-danger”></div>
If you choose to conditionally toggle a class in the set, use the following
ternary expression:
• <div v-bind:class=”[isActive ? activeClass : ‘’, error-
Class]”></div>
This would still add errorClass, but only activeClass when isActive
is true.
However, if you have several conditional types, this may get very ver-
bose. As a result, the object syntax may also be used within array syntax:
• <div v-bind:class=”[{ active: isActive }, errorClass]”></
div>

With Components
This section assumes understanding of Vue Components. You can skip it
and come back later.
When you use the class attribute on a custom object, such classes are
applied to the root element of the feature. This element’s existing classes
would not be overwritten.
For eg, if you declare this component:
• Vue.component(‘my-component’, {
• template: ‘<p class=”foo bar”>Hi</p>’
• })

Then when you use it, add the following classes:


<my-component class=”baz boo”></my-component>
The HTML will be:
• <p class=”foo bar baz boo”>Hi</p>
For class bindings:
60 Class and Style Bindings

• <my-component v-bind:class=”{ active: isActive }”></my-


component>
When isActive is true, the rendered HTML will be as follows:
• <p class=”foo bar active”>Hi</p>

Binding Inline Styles


Syntax of Objects
The object syntax for v-bind:style is simple - it almost looks like CSS, but it’s
a JavaScript object. For CSS property titles, you may use either camelCase
or kebab-case (with kebab-case, use quotes):

Copyright Attribution: Vuejs


v-bind style

To make the template smoother, it is always a good idea to attach directly


to a style object.
Copyright Attribution: Vuejs

Effective pattern

Once again, the object syntax is often combined with computed proper-
ties that return objects.

Syntax of an Array
You may add several type objects to the same element using the array
Class and Style Bindings 61

syntax for v-bind:style:


• <div v-bind:style=”[baseStyles, overridingStyles]”></div>

Prefixing automatically
When you use a CSS property in v-bind:style that includes vendor prefixes,
such as turn, Vue can automatically detect and apply the required prefixes
to the implemented styles.

Multiple Values
Starting from 2.3.0 and up, you can supply an array of multiple (prefixed)
values to a style object, such as:
• <div v-bind:style=”{ display: [‘-webkit-box’, ‘-ms-flexbox’,
‘flex’] }”></div>
This can only show the last value in the list that the browser recognizes.
Display: flex will be rendered in this illustration for browsers that accept
the unprefixed implementation of flexbox.

Conditional Class Bindings


Binding Fundamentals
We use the following syntax to bind a variable to a prop, class, or style:

Copyright Attribution:
Michaelnthiessen

conditional binding

If the value of className is blue-text, the class.blue-text will be added


to the span element. Normally, we shorten the linking syntax by deleting
v-bind, leaving us with just this:
Copyright Attribution:
Michaelnthiessen

conditional binding
62 Class and Style Bindings

However, the value of className will still be applied as a class to our


span tag.

Guard Expressions
There is a neat trick that we can use with the logical && (AND) to condi-
tionally add a class:

Copyright Attribution: Michaelnthiessen


Logical &&

This is referred to as a guard expression.


When useTheme is set to real, the class is set to whatever the theme
value is. Here, we have the boolean vector useTheme, and theme is the
value of the theme class. If the first value is right, the && (AND) operator
in Javascript can short-circuit.
Since all values must be valid for the expression to be accurate, if the first
is incorrect, there is no sense in testing whether the second is, because we
already know the expression corresponds to false. As a result, if useTheme is
set to false, the term evaluates to false and no dynamic class name is added.
If useTheme is set to correct, it will also evaluate the theme, and the
phrase will evaluate to the theme’s meaning. The value of the theme would
then be used as a classname.

Ternaries
We may do the same thing for ternaries.
If you’re not acquainted with the word, a ternary is essentially a short-
hand for an if-else statement.
They appear as follows:
• const result = expression ? ifTrue : ifFalse;
Class and Style Bindings 63

Or
• const result = expression
• ? ifTrue
• : ifFalse;
ifTrue is returned if expression evaluates to real. If we don’t, we’ll
get ifFalse.
Their biggest advantage is that they are brief and count as a single sen-
tence. This allows us to include them inside our models.
Ternaries come in handy when we need to choose between two separate
values inside the template:

Copyright Attribution: Michaelnthiessen


Ternaries

If darkMode is set to real, we use the class name dark-theme. Otherwise,


we go for a light-theme.

Computed Properties
The reasoning required to determine which class name to use may be a
little more difficult at times.
In these circumstances, it doesn’t really work within the template, so
Copyright Attribution: Michaelnthiessen

you’ll want to place it in a computed prop:

Computer properties
64 Class and Style Bindings

Copyright Attribution: Michaelnthiessen


Computer properties (...continued)

Examples
Class binding
Vue inline style bind
• <div v-bind:style=”{ color: activeColor, fontSize: fontSize
+ ‘px’ }”></div>

Vue class binding


• <div v-bind:class=”{ active: isActive }”></div>

Vue if echo class


• <div class=”defaultclass” :class=”condition?’ conditional-
classtoappend’:’’”></div>

Vue class binding


• <div v-bind:class=”[{ active: isActive }, errorClass]”></
div>

Class binding vue


• <div class=”static”
• v-bind:class=”{ active: isActive, ‘text-danger’:
hasError }”
• ></div>

Vuejs :class
• <div
• class=”static”
Class and Style Bindings 65
• v-bind:class=”{ active: isActive, ‘text-danger’:
hasError }”
• ></div>

Binding multiple class


Binding multiple class vuejs
• v-bind:class=”{ active: isActive, ‘text-danger’: hasError
}”
• // or
• :class=”{ active: isA
• v-bind:class=”{ active: isActive, ‘text-danger’: hasError
}”
• // or
• :class=”{ active: isActive, ‘text-danger’: hasError }”

Bind class
• <div v-bind:class=”{ active: isActive }”></div>

Dynamically style HTML by binding data to an element’s style


attribute
Use variant colours to style the background-colour of divs. The variant
colours are “green” and “blue”, we want a div with a green background-
colour and a div with a blue background-colour.
Copyright Attribution: Vuemastery

Example code
66 Class and Style Bindings

Copyright Attribution: Vuemastery


Example code

Rather than printing the variant’s colour into a p tag, use it to set the style
of a div’s background-colour. Instead of hovering over text in a p tag, we
can hover over coloured squares, which will change the product’s icon to
fit the colour hovered on.
First, we’ll add a colour-box class to our div, which will offer it a width,
height, and margin. Since we’re already printing “grey” and “blue” on the
page, we can use those variant colour strings and bind them to our style
attribute as follows:
Copyright Attribution: Vuemastery

Example code
Class and Style Bindings 67

Depending on our variant colours, we use an inline style to dynamically


set the background-colour of our divs ( variant.variantColour ).
We no longer need to print our divs now that they are styled by the
variantColour. As a result, we will remove the p tag and switch the @
mouseover to the div itself.

Copyright Attribution: Vuemastery


Example code

When we hover over the blue box, the blue socks show, and when we
hover over the green box, the green socks appear.
Let’s look at class binding now that we’ve understood how to do
style binding.

Copyright Attribution:
We already have the following in our database:

Vuemastery
Example code

We shouldn’t encourage users to press the “Add to Cart” button if this


boolean is incorrect, then there is no product in stock to add to the cart.
Fortunately, there is an HTML attribute called disabled that will disable
the icon.
We can use attribute binding to add the disabled attribute whenever
inStock is false, or rather not true: !inStock.
Copyright Attribution: Vue-
mastery

Example code
68 Class and Style Bindings

When inStock is false, our button is now disabled. However, this has
little impact on the appearance of the button. In other terms, the icon seems
to be clickable even though it is not.
Similarly to how we attached inStock to the disabled attribute of the
icon, we can add a disabledButton class to our button if inStock is false.
As a result, our icon would appear disabled.

Copyright Attribution:
Vuemastery
Example code

Copyright Attribution:
The button is now greyed out when inStock = false.

Vuemastery
Example code

To attach to the class of our button, we use the v-bind directive’s shorthand :
The inclusion of the disabled-button class is determined inside the
brackets by the truthfulness of the data property inStock.
In other terms, the disabledButton class is introduced while our product
is not in stock (!inStock ). Since the disabled-button class uses a grey back-
ground colour, the button becomes grey.
We’ve used our new skill class binding in conjunction with attribute
binding to disable and grayscale our button if our product inStock is false.

Conclusion
In this tutorial, we learned about different ways that we can style our Vue.
js application using class and style bindings with multiple style arrays,
v-bind, inline styles, object and array syntax.
Chapter #07Conditional Rendering 69

Copyright Attribute: Morioh


Conditional
Rendering
If-else in context of Vue.js

I
n the web development industry, we keep hearing the news of some
new frameworks being launched now and then. Some frameworks
hold their integrity and are not getting weak even in this competi-
tive environment. Vue.js is one such progressive framework that
web developers still use to develop the website’s user interface. The core
library of this development framework focuses on the view layer only. It is
easy to integrate with other libraries and can be picked up without much
struggle. There are many modern solutions that this framework provides,
like powering the sophisticated single page application when it is used in
collaboration with modern tools and support libraries.
There are many reasons why JavaScript frameworks are preferred over
other web development frameworks all around the world. The function-
alities they provide, the features they let the developers add might not be
available with other development platforms. Vue, like other development
70 Conditional Rendering

frameworks, provides easy development options to the developers. Going


ahead, we will learn about why one should use Vue for their web UI devel-
opment projects, conditional rendering and some other information about
the Vue framework.

Conditional Rendering
As far as a dynamic web application is concerned, conditional rendering
is an inseparable part. With the help of conditional rendering, it becomes
easy to toggle a particular element in the DOM. The process of toggling
works on certain conditions given by the developer.
As Vue.js is an ahead of time framework for building user interfaces, the
libraries focus on the view layer only. With conditional rendering, it becomes
easy to go through the blocks, implement user-defined conditions and inte-
grate with other functions. As a result, powerful single-page applications
are created that are blended with modern tooling and supporting libraries.
Vue.js provides several ways of conditional rendering. Developers can
use them according to the purpose of the software and their own needs.
The primary directives of conditional rendering are as follows:
• v-show
• v-if
• v-else
• v-else if
In this article, there will be a detailed description of what these direc-
tives mean and which directive can be used for what motive, along with
descriptive examples.

v-if
The directive v-if is commonly used to render a particular block. But this
type of conditional rendering is only possible if the expressions of the direc-
tive return a true value. This means v-if will neither hide the element nor
render anything until the system passes the value or the given expression
becomes true.

For example,
• <!-- This div is conditionally rendering -->
• <div v-if=”isBool”>
• <p>This is a paragraph</p>
• </div>
Conditional Rendering 71

Since v-if is a directive, it must be associated with a single element. But


what if somebody wants to toggle more than a single element? v-if can also
help with that easily. This is another interesting fact about the v-if direc-
tive. It can be applied to the template block even if the user doesn’t want to
render anything between them. Either a child component or a lot of other
elements is present in that block. The final rendered result will not consist
of the <template> element.
As far as the type of rendering is concerned, v-if is considered more
accurate because it ensures that everything inside the conditional block,
including event listeners and child components, is appropriately destroyed.
It also facilitates the recreation of these elements during toggles.
Additionally, if the condition is false on the initial step of rendering, the
v-if directive will simply not execute. The conditional block will not get
rendered until and unless the given condition becomes true for the first
time. This feature of v-if often makes developers call it ‘lazy’ as compared
to other directives.

For example,
• <!-- This template is conditionally rendering -->
• <template v-if=”isBool”>
• <h1>This is a Heading</h1>
• <p>This is a paragraph</p>

• <!-- A child component -->
• <Hello msg=”Hello Vue” />
• </template>

v-else
Like conditional statements of other programming languages, v-else can
be used along with v-if if there is more than one condition. v-else condi-
tional rendering is instrumental when the user wants to render between
any of the two code blocks. It is essential to keep in mind that v-else only
gets executed when it appears right after the v-if block or a v-else if block.

For example,
• <!-- This div is conditionally rendering -->
• <div v-if=”Math.random() > 0.5”>
• Now you see me
72 Conditional Rendering

• </div>
• <div v-else>
• Now you don’t
• </div>

Similar to v-if, v-else rendering can also be applied to the template block.

For example,
• <!-- This div is conditionally rendering -->
• <div v-if=”isVar == true”>
• <h1>This is a Heading</h1>
• </div>
• <!-- v-else on template block -->
• <template v-else>
• <p>This is a paragraph</p>
• <!-- A child component -->
• <Hello msg=”Hello Vue” />
• </template>

v-else if
v-else if acts as an “else if block” for the v-if directive. Unlike v-else, it can
be implemented multiple times.

For example,
• <div v-if=”type == ‘car’”>
• <p>Car</p>
• </div>
• <div v-else-if=”type == ‘book’”>
• <p>Book</p>
• </div>
• <div v-else-if=”type == ‘animal’”>
• <p>Animal</p>
• </div>
• <div v-else>
• <p>None of the ablove</p>
• </div>

v-show
v-show is another option for displaying elements. The usage is, however,
Conditional Rendering 73

similar to that of v-if. The syntax of v-show can be understood with the
help of the following example,

• <p v-show=”isBool”>This paragraph is not hidden</p>


• <p v-show=”!isBool”>This paragraph is hidden</p>

The difference between v-if and v-show is that the elements used inside
the v-show directive are always going to remain and rendered in the DOM.
v-show only does the job of toggling the display CSS property of the element.
But, it can neither be executed along with the <template> element, unlike
above mentioned conditional rendering directives, nor it is compatible to
work with v-else.
The reason why developers use v-show is its simplicity. The elements
get rendered regardless of what the initial toggling has to offer. v-show
runs on CSS-based toggling. The initial rendering costs for the same are a
bit on the higher side.
If the developer needs to toggle the blocks regularly, v-show is the prefer-
able directive of all. But on the other hand, if the conditions of the block are
unlikely to change for a long duration during the runtime, v-if will prove
more efficient in terms of cost and usage.

Why Developers Should Choose Vue.js For Web UI


Development
There are many UI development frameworks out there then why Vue use
them?
Copyright Attribute: Vtnetzwelt

Why Developers Should Choose Vue.js


74 Conditional Rendering

Design plays a significant role in website development and is one factor


that determines how the visitors will accept the website. A website looks
and behaves when people come and try to interact with the websites
dramatically impacts them. Most people decide if they want to stay on a
website or leave it within a few seconds of opening it. The reason is design.
If the design of the web page they see is appealing, simple, and focused on
the main goal, they will stay. If there are distractions, they might remain
for some time, but eventually, they will leave, and they might not come
back again. After React.js, Vue.js is the most loved framework if we believe
StackOverflow.
Let’s look at the reasons why a developer should choose Vue.js for web
UI development:

• Small Size Apps:


The first reason why most people use Vue is because of the small size of its
application. The size of the application is generally between 18-21 kBs, and
that is considered to be reasonably small. Even though the size of the app is
small, it doesn’t affect its performance or speed, and that is why they are also
the reasons mentioned below. Developers can choose this framework without
any confusion for both small and extensive web development UI projects.

• Easy To Learn:
Developers who have never used Vue can learn how to use it quickly. The
framework is easy to understand, and if the developers give it time and dedi-
cation, they can easily understand it. Also, with practice, they can get a hold
of this. This is something that attracts a lot of UI developers towards Vue.js.

• Better Performance:
The applications and the interface created by the Vue are great. The reason
behind this is that this framework allows the developers to avail excellent
performance. Developers choose Vue because of this reason as well. The
framework is capable of handling high frame rates.

• Easy To Integrate:
Because this framework is based on JavaScript, it is easy to integrate it with
any existing application where integrated JS is possible. This feature of the
framework helps the developers to create other applications from scratch
and introduce the elements of Vue into it later.
Conditional Rendering 75

• Flexible:
Web development needs flexibility, and that is a feature that Vue.js provides.
This framework allows the developers to write templates in HTML and
JavaScript and execute them directly into the browser. This is something
that gives back the power in the hands of the developers. They can customise
the templates according to the requirements, increasing the quality of the
web UI by a significant margin.

Copyright Attribute: appinventiv


Benefits of choosing Vue.Js for UI development

Pros And Cons Of Using Vue.js

Pros:
• Small Size Of The App
• Virtual DOM (Document Object Model) rendering and performance
• High Performance
• Two-way data binding
• Easy To Use

Cons:
• Language barrier
• Reactivity Complex
• Over flexibility risk
• Resources are limited
76 Conditional Rendering

Copyright Attribute: 9Series


Benefits of choosing Vue.Js for UI development

Conclusion
As said in the article, this web UI framework has many features that make it
suitable for all modern development needs. Many web development compa-
nies around the world use Vue.JS in their main web development projects.
With its base being JavaScript, the framework already has a big community
and helps with the framework in many ways. The conditional rendering
statements used in the framework have been described for understanding.
Developers need to understand the importance of this UI development
framework and use it in the best capacity. Web pages, single-page applica-
tions, or other types of web applications, all their UI’s can be designed with
the help of Vue. You can keep exploring more about Vue.
Chapter #08 List Rendering 77

CodeSource.io
List Rendering
Dynamic list rendering to provide a
collection of equally grouped items

L
ist rendering is a technique often used in front-end web creation.
The consumer is often presented with a set of equally grouped data
in a succinct and comfortable format using dynamic list rendering.
We will see collections of content in various places on almost any
web application we use. We’ve grown used to having a list of trends, posts,
potential supporters, etc., on the dashboard. The material reflected in these
lists is determined by a variety of variables, including our Twitter feed, who
we follow, and our likes. Hence, we should state categorically that all this
data is dynamic. Let’s learn how to use the v-for directive in Vue to build
dynamic lists. We’ll also go into the details of whether the main attribute
should be included in this situation.

Lists
Lists generate a windowed list (row) of objects, with users seeing just the
visible rows (e.g., FixedSizeList, VariableSizeList). Lists render rows using
a Grid (internally), relaying props to the inner grid.
78 List Rendering

Grid
The grid creates virtualized tabular data around the vertical and horizontal
axis (e.g., FizedSizeGrid, VariableSizeGid). It just renders the grid cells
necessary to fill themselves depending on the horizontal/vertical scroll
positions currently in use.

How Does Virtualization of Lists Work?


“Virtualizing” a list of items entails holding a window and repositioning
it within the set. Windowing in react-virtualized works is accomplished
by the following:
• Taking a minimal container DOM element with relative positioning
(e.g., ul>) (window).
• Using a large DOM element to facilitate scrolling.
• The child components are positioned inside the jar, with their top, left,
distance, and height styles set.
Rather than rendering thousands of objects from a list concurrently

Copyright: addyosmani

Rendering with visualization


List Rendering 79

(which may delay initial rendering or impair scroll performance), virtu-


alization concentrates on rendering only the things available to the user.
This will help maintain a quick list rendering speed on mid-range to
low-end computers. As the user scrolls, you can fetch/display additional
objects by unloading previous entries and replacing them with new ones.

Using v-for for List Rendering


The v-for directive is used to display a list of items determined by a data
source. The directive may be used on a prototype feature and includes the
following syntax:

Copyright: CSS tricks


V- for directive

Consider an example of this in action. To begin, let us assume that we


already have a set of tweet data:

Copyright: CSS tricks

Code for V-for directive using tweets


80 List Rendering

A tweet is a list of tweet items, each con-


taining information about an individual
tweet—a unique id, the account’s name/handle,
the tweet address, and so on. Now, let’s attempt
to collect tweet components based on this data

Copyright: CSS tricks


using the v-for directive.
To begin, we’ll build the Vue instance—the
application’s core. We’ll mount/attach our
instance to a DOM element in the id app and
provide the tweets collection in the data object Creating vue
for that instance.
We’ll now build a tweet component to be used by our v-for directive to
make a chart. We’ll generate a component called tweet-component using
the global Vue.component constructor:

Copyright: CSS tricks

V-for directive using tweets


List Rendering 81

There are a few noteworthy points here.


• As specified in the prop validation criteria, the tweet-component expects
a tweet object prop (props: {tweet: Object}). Vue can emit alerts if the
component is made with a tweet prop that is not an object.
• Using the Mustache syntax:{{}}, we connect the properties of the tweet
object prop to the component template.
• Bulma’s Box element is adapted in the part markup since it bears a
striking similarity to a tweet.
In the HTML template, we’ll need to build the markup for the location
of our Vue application (i.e., the element with the id of the app). We’ll use
the v-for directive to collect tweets within this markup. Given that we’ll be
iterating over tweets, the tweet is an acceptable alias to use in the directive.
Additionally, we’ll move the iterated tweet object as props to each made
tweet component so that it can be accessed inside the component.

Copyright: CSS tricks


HTML Template for using tweets

Maintaining State
By default, as Vue updates a collection of items made with v-for, it employs
an “in-place patch” technique. If the order of the data items changes, Vue
may patch each feature in place to ensure it accurately represents what
should be made at that specific index.
Although this default mode is effective, it is only appropriate when
your list render performance does not depend on the child component or
temporary DOM state (e.g., form input values).
To provide Vue with a clue that it can trace the identity of each node, and
therefore reuse and reorder existing items, you must provide each object
with a specific main attribute:
Copyright: CSS tricks

Applying key attribute


82 List Rendering

Where appropriate, it is advisable to use the main attribute with v-for,


whether the iterated DOM material is easy or you deliberately depend on
default actions for efficiency gains.
Because the key is a common method for Vue to classify nodes, it has
additional applications unrelated to v-for, as we will see later in the guide.

Key
A key attribute is typically specified for each iterated element within a
rendered v-for list. This is because Vue uses the main attribute to generate
special bindings for the identification of each node.
Let’s explain further—if our list undergoes some complex UI shifts (e.g.,
the sequence of list objects is shuffled), Vue would prefer to modify the data
inside each unit rather than shifting the DOM entities appropriately. This is
unlikely to be a concern in most situations. However, in some cases where
our v-for list is dependent on the state of the DOM and/or child component,
this may result in some unexpected actions.
We’ll incorporate this new input area into the tweet-template compo-
nents as follows:

Copyright: CSS tricks

Tweet component

Assume we wanted to add another new function to our application.


This functionality will encourage the consumer to arbitrarily scramble a
collection of tweets.
List Rendering 83

To accomplish this, we can begin by adding a Shuffle! button to our


HTML template:

Copyright: CSS tricks


Adding Shuffle

We’ve added a @click event listener to the button, which when activated,
initiates a shuffle process. We’ll create the shuffle method in our Vue case,
which will be responsible for randomly shuffling the tweets collection in
the instance. To execute this, we’ll use lodash’s _shuffle method:

Copyright: CSS tricks

Addition of click

Vue would not generate special bindings for each tweet node since we did
not use the main attribute. As a consequence, when reordering the tweets,
Vue takes the more efficient method of simply changing (or patching) the
data in each element. Because the temporary DOM state (i.e., the inputted
text) is retained, this unintentional mismatch occurs.
84 List Rendering

Methods for resolving list performance problems


1. Pagination
Pagination enables you to make data in pages rather than all at once. This
way, you can effectively monitor the amount of data shown on the website
without undue strain on the DOM tree.
Although most React UI libraries have a pagination feature, if you’re
looking for a fast way to enforce pagination without installing a UI library,
you might want to check out react-paginate. The library generates a pagi-
nation component that accepts certain props and aids in data navigation.
Run the following code in your terminal to install the library. Please
note, Part 1 and Part 2 of the Pagination implementation code are to be
written together.

Copyright: Log rocket

Pagination implementation code (Part 1)

Following installation, you should configure your app component to


paginate the data rather than rendering it all at once.
In this case, we’re storing the pagination information in our paginating
state. Rather than making the whole data set at once, we make only the
present data, which we obtain by splitting the key data set according to the
current offset and the number of records to be shown on the page.
As a prop, the ReactPaginate function accepts an event handler that is
invoked whenever the page shifts. When the page loads, the event controller
List Rendering 85

Copyright: Log rocket

Pagination implementation code (Part 2)

estimates the initial offset, which is then used to determine the current
data to view.

2. Infinite Scroll Method


Infinite scroll is another way to make a large amount of data. When you
86 List Rendering

scroll down the list, infinite scroll adds data to the end of the tab. Just a
portion of the data is accessed as the page first loads. More information is
added when you move down the list.

Conclusion
A popular method to view a list of data is to create a list in the browser. This
is very different from how you would address this with one of the other
common UI frameworks, such as Vue or Angular. In some other frameworks,
you will iterate directly in HTML using personalized directives such as
v-for or ng-for. With the response, iteration is accomplished by the use of
native JavaScript. Thus, in React, you can iterate over an array and generate
a list using the map() method. Although React lacks the syntactic sugar of
ng-for or v-for, we can achieve the same impact using the JavaScript map
function. To update objects in a made list, Vue employs an in-place patch
strategy. Rather than recreating the list, Vue locates the object that was
modified and changes it. This is significantly faster than recreating and
rendering the list.
Chapter #09 Events 87

Rip Tutorial

Events
Events are a great way to build
interactivity in your web applications

Introduction
Events or occurrences arise in the machine you’re programming, which
the system informs you of so you can react accordingly. If a user clicks a
button on a website, for example, you may want to answer by showing an
information box.
When an incident happens in the system you’re programming, the system
emits (or “fires”) a signal of some sort and creates a trigger for a response
to be taken immediately (that is, a code to run).
88 Events

Each accessible event has an event handler, which is a block of code


(typically a JavaScript function created by you as a programmer) that is
executed when the event occurs. We call registering an event handler a
block of code that is specified to run in response to an event. Remember that
event handlers and event listeners are always used interchangeably for our
purposes, though they do fit together, strictly speaking. The listener is the
code that is executed when an event occurs, and the controller is the code
that is executed in response to the event occurring.

Using event listeners


In web design, event listeners are one of the most commonly employed
JavaScript structures. They allow us to add interactive features to HTML
elements by “listening” to events on the web, such as when a user clicks a
button, presses a key, or when an element loads.
We should do something after an event occurs.
Load, select, touchstart, mouseover, and keydown are the most popular
events to “listen out for”. MDN’s Case Reference guide contains a list of all
DOM events.
Below, we have listed three separate ways to make a JavaScript event listener:
• The global onevent attributes in HTML
• The event method in jQuery
• The addEventListener() method of the DOM API

How to Make a JavaScript Event Listener


We can listen to any of the events specified in MDN’s Event Reference,
including touch events, using native JavaScript. It’s the most performance-
friendly way to bring dynamic features to HTML elements since it doesn’t
need the usage of a third-party library.
The addEventListener() method, which is integrated into any modern
browser, can be used to build an event listener in JavaScript.
Using simple JavaScript and the addEventListener() method, is how our
alarm button example would look.
In native JavaScript, we must first pick the DOM variable on which the
event listener would be applied. The querySelector() method finds the first
variable that fits a selector. As a result, it selects the first <button> element
on the page in our case.
When the user presses the switch, the custom alertButton() feature is
named as a callback function.
Events 89

Copyright Attribution: Envato Tuts+


Javascript event listener

Finally, the event listener is added. Using the dot notation, we must
always append the addEventListener() method to a pre-selected DOM vari-
able. We specify the event we want to listen to (“click”), then the name of the
callback feature (alertButton), and finally the meaning of the useCapture
parameter in the parameters.

How to Enable All Buttons Functionality


As a result, the code above applies the alert function to the page’s first key.
But how will we go about making both buttons have the same functionality?
To accomplish this, we’ll use the querySelectorAll() process, loop through
the items, and assign an event listener to each button: Copyright Attribution: Envato Tuts+

Adding querySelectorAll()

We must loop through the nodes to add a click event listener to each
button since querySelectorAll() returns a NodeList rather than a single
90 Events

element. The code above, for example, would produce three click event
listeners if there are three buttons on the page.
With addEventListener(), you can only listen to one event at a time.
You’ll need to build a second event listener rule if you want the custom
alertButton() feature to fire on a certain event kind, such as mouseover:

Copyright Attribution:
Envato Tuts+
Adding addEventListener()

Event Handlers
Events are signals sent from inside the application window that alert the
user to changes in the browser or operating system. Event handler code may
be written by programmers to operate when an event occurs, enabling web
pages to react correctly to changes.

Properties of event handlers


The event handler property used in this case is the onclick property. It’s
exactly the same as any other property on the button (for example, btn.
textContent or btn.style), but it’s a rare type in that when you configure it
to be identical to a code, the code is executed when the button’s event fires.
There are several event handler properties to choose from:
• btn.onfocus and btn.onblur — As the button is focused and unfocused,
the colour changes; click the tab to focus on the button, then press the
tab again to focus away from it. When they are oriented, they are often
used to show details regarding filling in form fields or to display an error
message if a form field is filled with an incorrect value.
• btn.ondblclick — Just when the icon is double-clicked does the
colour shift.
• window.onkeypress, window.onkeydown, and window.onkeyup —
As a key on the keyboard is pushed, the colour switches. The keypress
event denotes a full press (button down, then up), while keydown and
keyup denote just the key down and key up portions of the keystroke,
respectively. Note that registering this event handler on the button itself
would not work; however, we must register it on the window variable,
which reflects the entire browser window.
Events 91

• btn.onmouseover and btn.onmouseout — The colour of the icon varies


as the mouse cursor hovers over it or pushes away from it, respectively.

Event Modifiers
Within event handlers, calling event.preventDefault() or event.stopPropa-
gation() is a standard requirement. While we can do this conveniently inside
methods, it would be preferable if the methods should focus solely on data
logic rather than DOM case specifics.
Vue offers event modifiers for v-on to solve this problem. Remember
the modifiers are dot-denoted directive postfixes.
• .stop
• .prevent
• .capture
• .self
• .once
• .passive

Copyright Attribution: Vuejs

Use of event modifiers

When using modifiers, the order is important since the relevant code is
created in the same order. As a result, v-on:click.prevent.self prevents all
clicks, while v-on:click.self.prevent prevents just clicks on the feature itself.
92 Events

The .passive modifier in Vue corresponds to the passive alternative in


addEventListener.

Copyright Attribu-
tion: Vuejs
.passive modifier

The .passive modifier is particularly useful for optimising mobile device


efficiency.
If you use .passive and .prevent at the same time, .prevent will be
skipped, and your window will most likely show an alert. Remember that.
passive tells the browser that you don’t want the event’s default behaviour
to be overridden.

Key Modifiers
We frequently need to look for specific keys while listening for keyboard
events. When listening for important events, Vue helps you to apply key
modifiers to v-on:
Copyright Attribu-
tion: Vuejs

Using v-on.

Event bubbling and capture


When two handlers of the same event form are triggered on the same ele-
ment, event bubbling and capture are two mechanisms that characterise
what happens. To make it simpler, let’s look at an illustration.
Events 93

This is a clear illustration of how to show and hide a <div> with a video
feature inside it:
The video is shown when the <button> is clicked by modifying the
class attribute on the <div> from secret to displaying (the example’s CSS
includes these two classes, which places the box off the screen and on the
screen, respectively):

Copyright Attribution:
MDN Webdocs
Using <div>

After that, we add two more onclick event handlers, one to the <div> and
the other to the <video>. The box can now be covered when the area of the
<div> outside the video is chosen, and when the video itself is selected, the
video should begin to play.

Copyright Attribution: MDN Webdocs

Using <div>

However, there is a problem: when you pick the film, it begins to play,
but the <div> is obscured at the same time. Since the video is contained
inside the <div> — it is a part of it — clicking it activates any of the above
event handlers.

Bubbling and capturing described


Modern browsers operate two stages while an event is shot on an element
with parent elements (in this instance, the <video> has the <div> as a parent),
the capturing process and the bubbling phase.
94 Events

In the capturing phase:


• If the element’s outermost ancestor (<html>) has an onclick event handler
recorded for the capture process, the browser can execute it.
• Then it goes on to the next entity within <html> and repeats the process,
then the next, and so on before it reaches the final selected element.
In the bubbling process, the exact opposite occurs:
• The browser tests to see if the selected entity has an onclick event handler
for the bubbling process, and if it does, it executes it.
• Then it repeats the process for the next immediate ancestor node, then
the next, and so on before it hits the <html> element.

Copyright Attribution: MDN Webdocs


Process of <video>

Both event handles are registered for the bubbling process by design in
modern browsers. When you pick the video in our current case, the event
bubbles outwards from the <video> element to the <html> element. On
the way, you’ll encounter:
It locates and executes the file.onclick... handler, enabling the video to
begin playing.
The videoBox is then discovered, onclick... handler and operates it, then
the video is hidden as well.

StopPropagation()
This is a very troublesome action, but there is a solution! The basic Event
object has a feature named stopPropagation() that, when called on a han-
dler’s event object, causes the first handler to be executed but the event
to not propagate further up the chain, resulting in no further handlers
being executed.
Events 95

As a result, we will resolve our current issue by modifying the second


handler function in the previous code block to:

Copyright Attribution:
MDN Webdocs
Using StopPagation()

Preventing default behaviour


You can find yourself in a position where you want to prohibit an event
from doing its default actions. A web type, such as a custom login form, is
the most popular example. When you fill in the specifics and click the send
button, the data is sent to a specific location on the server for analysis, and
the window is redirected to a “progress alert” page of some kind (or the
same page, if another is not specified.)
The problem arises where the user cannot upload the data correctly; as a
creator, you try to avoid the data from being sent to the server and therefore
display an error message that explains what went wrong and what needs to

Copyright Attribution:
MDN Webdocs

Preventing behavior
96 Events

be done to fix it. While certain browsers have automated type data valida-
tion capabilities, many do not, so you should not focus on them and instead
perform your own validation tests. Let’s take a peek at a simple scenario.
To begin, fill out the HTML form on the previous page with your first
and last names.

Delegation of an event
Bubbling helps you to take advantage of event delegation, which is based
around the idea that if you want any code to run while you pick each of a
vast range of child components, you can set the event listener on their parent
and make events that happen on them bubble up to their parent rather than
trying to set the event listener on each child separately. Remember that
bubbling means first looking for an event handler on the element where
the event is shot, then going up to the element’s parent, and so on.
If you want each list item to show up a notification when it is picked,
you should set the click event listener on the parent <ul>, and events will
bubble up from the list items to the <ul>.

Conclusion
At this stage, you should know everything there is to know about web events.
As previously stated, events are specified in browser Web APIs and are not
part of the core JavaScript.
Often, various event models are found in different environments where
JavaScript is used, ranging from Web APIs to other fields such as browser
WebExtensions and Node.js (server-side JavaScript). We don’t expect you to
grasp any of these concepts right away, but understanding the fundamentals
of events can help you progress while you study web creation.
Another factor worth noting at this point is that events aren’t special
to JavaScript; most programming languages have an event model, but
the way it operates varies from JavaScript. In reality, the event model
for web pages in JavaScript varies from the event model for JavaScript
in other environments.

You might also like