Professional Documents
Culture Documents
TECHNOLOGY
YOUR HANDY GUIDE TO EVERYDAY
to
(Part - 1)
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 #
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
37 Computed Properties
Why are computed properties the best for implementing
complex logic, and how can it be done?
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
TECHNOLOGY
YOUR HANDY GUIDE TO EVERYDAY
Published by 9.9 Group Pvt. Ltd. (Formerly known as Nine Dot Nine (Part - 1)
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
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
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
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.
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.
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.
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.
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.
Document
Root element:
(html>
Element: Element:
(head> (body>
Copyright Attribution: www.altexsoft.com
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.
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
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
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.
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
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”>
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
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.
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): -
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.
Vue.js ESM
18 Vue.js installation
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”
• }
• }
Webpack
The mode option is available in Webpack 4+:
• module.exports = {
• mode: ‘production’
• }
20 Vue.js installation
Rollup
Apply rollup-plugin-replace
Browserify
You can make changes to the bundle by using the global envify transform.
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
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
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
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.
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’)
• 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.
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
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.
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,
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.
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’)” />
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 ()
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.
• 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.
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()
• }
• }
• 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>
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
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
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:
Classname applied
Let’s build a sample with two buttons and an inline expression that
increments and decrements the margin variable on the click event:
Building a sample
a style object in the model and use it in conjunction with the v-bind:style
directive.
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.
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.
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
Adding data
Output
Effective pattern
Array Syntax
To apply a collection of classes, we may transfer an array to v-bind:class:
Class and Style Bindings 59
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>’
• })
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
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.
Copyright Attribution:
Michaelnthiessen
conditional binding
conditional binding
62 Class and Style Bindings
Guard Expressions
There is a neat trick that we can use with the logical && (AND) to condi-
tionally add a class:
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:
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
Computer properties
64 Class and Style Bindings
Examples
Class binding
Vue inline style bind
• <div v-bind:style=”{ color: activeColor, fontSize: fontSize
+ ‘px’ }”></div>
Vuejs :class
• <div
• class=”static”
Class and Style Bindings 65
• v-bind:class=”{ active: isActive, ‘text-danger’:
hasError }”
• ></div>
Bind class
• <div v-bind:class=”{ active: isActive }”></div>
Example code
66 Class and Style Bindings
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
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
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
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
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
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,
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.
• 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.
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
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.
Copyright: addyosmani
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
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:
Tweet component
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:
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
estimates the initial offset, which is then used to determine the current
data to view.
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
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.
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.
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
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
Copyright Attribu-
tion: Vuejs
.passive modifier
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.
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.
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.
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
Copyright Attribution:
MDN Webdocs
Using StopPagation()
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.