A Complete Guide To VueJS by This Dot Authored by Bilal Haidar
A Complete Guide To VueJS by This Dot Authored by Bilal Haidar
js
By Bilal Haidar
2
© 2020 This Dot Labs
All Rights Reserved. No part of this publication may be reproduced, stored in a retrieval system, or
transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise,
without the prior written permission of This Dot Labs. To contact This Dot Labs regarding publication
rights, email [email protected].
The information in this publication is provided for information only, is subject to change without notice,
and should not be construed as a commitment by This Dot Labs. This Dot Labs assumes no responsibility
or liability for any errors or inaccuracies that may appear in this publication, present or future.
This Dot Labs and This Dot Media are registered trademarks of This Dot Inc. Related logos and symbols,
therefore, are property of This Dot Inc, and may not be reproduced, stored in a retrieval system, or
transmitted, in any form or by any means, electronic, mechanical, photocopying, recording.
Founded in 2016, This Dot Labs is a modern web consultancy focused on helping companies realize their
digital transformation efforts. For expert architectural guidance, training, or consulting in React, Angular,
Vue, Web Components, GraphQL, Node, Bazel, or Polymer, contact us today at [email protected].
Press Contact
Tracy Lee
CEO, This Dot Labs
thisdotlabs.com
408-506-9660
3
Table of Contents
A Word from the Author 4
Introduction 5
Bonus: Vue 3 85
In Closing 91
4
Introduction
From the onset, I’d like to make it clear that this is not a tutorial, but a comprehensive resource on Vue.js
for anyone wanting to deeply understand this framework. It will contain detailed information on internal
structures, complementary frameworks, components, and how to integrate everything to make Vue.js
work best for you. Those who are familiar with my articles, and follow my work, may expect me to be
writing a step-by-step tutorial, but this guide will feel very different from my typical publications.
This guide will help you begin your journey of learning and coding in the Vue.js framework- specifically
version v2. I won’t assume any prior knowledge in Vue.js or JavaScript, and I will provide the resources
you need to learn it in order to develop stunning Web apps.
It’s preferable, however, that you have some experience in, or basic knowledge of HTML and CSS.
The guide is lengthy, and contains many external links to supplement your learning. However, you should
feel free to go from section to section, or chapter to chapter as you need, or as your experience allows.
I’ve come across hundreds of articles, videos, and books on this topic, many of which are remarkable.
Before beginning my own guide, I feel compelled to share them with you.
5
- Learn ES6 [EcmaScript 2015] - A free resource to learn ES6 by FreeCodeCamp
(https://www.freecodecamp.org/news/want-to-learn-es6-take-this-free-23-part-course-and-becom
e-a-javascript-ninja-55002db1ff74/).
For those who prefer reading a physical book, here are my top recommendations:
- Web Design with HTML, CSS, JavaScript and jQuery Set
(https://www.amazon.com/Web-Design-HTML-JavaScript-jQuery-dp-1118907442/dp/1118907442
/ref=mt_paperback?_encoding=UTF8&me=&qid=)
Choose whatever resource(s) you want. Make sure you have grasped some basic knowledge of
JavaScript before you proceed with learning Vue.js.
The Vue.js team has done a great job of producing thorough documentation (https://vuejs.org/v2/guide/),
which I personally used when I first started learning about Vue.js. The documentation is well maintained,
and is updated with every new release.
There are a ton of available online resources to help you learn Vue.js. Here’s the list of courses and
books I highly recommend:
6
Free Vue.js resources
- Vue JS 2 Tutorial
(https://www.youtube.com/playlist?list=PL4cUxeGkcC9gQcYgjhBoeQH7wiAyZNrYa) by The Net
Ninja. This channel is another essential resource. He offers high-quality courses on many other
topics as well.
Make sure that you check out all, or some, of the above courses before continuing with the rest of this
guide. Practice, practice, and then practice some more. Understanding theory is only one part of the
journey. You really get to know all of the framework’s aspects when you are willing to jump in and get
your hands dirty.
Here’s a selection of the most widely used code editors for Vue.js and JavaScript:
- Bracket (http://brackets.io/)
- Atom (https://atom.io/)
- Sublime (https://www.sublimetext.com/)
These code editors are also used as normal text editors. Find one that best suits you.
7
For instance, VS Code has the Vetur (https://marketplace.visualstudio.com/items?itemName=octref.vetur)
extension. I cannot imagine developing Vue.js apps without installing this plugin. This extension offers the
following features, and more:
- Syntax-highlighting
- Snippet
- Emmet
- Linting / Error Checking
- Formatting
- Auto Completion
- Debugging
To install Vetur extension, follow the basic steps below as shown in Figure 1:
1. Open VS Code
2. Click the Extensions menu
3. Type `vetur` and hit Enter
4. Once located, click the orange `Install` button
8
Section 4: Vue CLI
The Vue CLI (https://cli.vuejs.org/) is provided and maintained by the Vue.js team. It allows you
to start rapidly developing with Vue.js, by taking care of creating the Vue.js project structure for
you. It comes in two flavors: Command Line CLI, and Graphical UI CLI.
The CLI supports out-of-the-box Babel, TypeScript, ESLint, PostCSS, PWA, Unit Testing, and
End-to-end Testing. It has a built-in plugin system that allows developers to extend its
functionality by developing their own plugins. Moreover, the CLI is highly configurable, which
means that there is no need to eject its WebPack (https://webpack.js.org/) configuration when a
developer wants to customize it further.
The CLI requires Node.js version 8.9 or above (8.11.0+ recommended). Make sure it’s installed
on your computer before you proceed.
You can check the version of the installed CLI by running the following command:
9
The CLI asks a few questions to help you customize your app according to your requirements.
For the scenario at hand, I will select the following options:
First, select the manual option to allow you to customize the features of this app as shown in
Figure 2:
10
Figure 3: Vue CLI installation - select options
Having `Babel` installed, and configured, allows you to write JavaScript ES6 code.
We will cover the following topics in-depth as we go along, or as they come up.
The `CSS Pre-processors` option adds capabilities to use Sass, Less, and Stylus, in the app.
The `Linter/Formatter` option adds support for both ESLint, and Prettier, in the app.
The `Unit Testing` and `E2E Testing` options add testing capabilities to the app.
Once done with your selections, hit the {Enter} key on your keyboard.
Type `n` to use the history mode for the router as shown in Figure 4:
10
11
Figure 4: Vue CLI installation - router
Select the `Sass/SCSS (with node-sass)` option for the CSS pre-processor, as shown in Figure
5:
11
12
Figure 5: Vue CLI installation - Sass
Select the `ESLint + Prettier` option for the linter/formatter config as shown in Figure 6. This
enables you to use, and benefit from, both linting, and formatting for your code:
12
13
Figure 6: Vue CLI installation - ESLint + Prettier
int on save option for the additional lint features, as shown in Figure 7. When
Select the L
you save your code files, the CLI runs the linter, and formatter, on any saved file. It will
immediately report any problems on the command line / terminal. This is the easiest option to
use when starting with Vue.js. Later on, I recommend using the L int and fix on commit
option. The linter, and formatter, in this case, will only check the commit payload, will report the
problems, and will fix any formatting discrepancies. This is much faster than checking all of the
project files!
13
14
Figure 7: Vue CLI installation - Linting
Select the `Jest` option for the unit testing solution as shown in Figure 8. You may choose
another option, like `Mocha and Chai`. However, in this guide, I will only cover Jest:
14
15
Figure 8: Vue CLI installation - Jest for unit testing
Select the `Cypress` option for the E2E testing solution as shown in Figure 9. Cypress is the
most widely used framework for building and running End-2-End tests. We will cover this topic,
in more depth, down the line.
15
16
Figure 9: Vue CLI installation - Cypress.io for E2E testing
Select the `In dedicated config files` option to save all the configuration settings inside of their
own config files as shown in Figure 10. This is better for separating concerns, and keeping
each service configuration isolated from the other.
16
17
Figure 10: Vue CLI installation - save configuration
Finally, type `y` to save all the settings as a template. This can be reused later to create more
Vue.js projects as shown in Figure 11. This saves you the time of choosing the same options
again and again.
17
18
Figure 11: Vue CLI installation - save as a preset
You will be prompted to name this new template. I’ve used `best_vue_settings` as its name as
shown in Figure 12.
18
19
Figure 12: Vue CLI installation - naming the preset
The Vue CLI starts scaffolding your project, taking into consideration all of your options, while
running the CLI.
The CLI takes a few minutes before readying your project for use.
Now that the project is created, navigate to the app folder, and run it using the command as
shown in Figure 13.
19
20
Figure 13: Running the Vue.js app
Now that the app is running, view it live in a browser, by following the steps:
1. Open a new browser instance. You can select Google Chrome, Microsoft Edge, Firefox,
etc.
20
21
Figure 14: Vue.js app running inside a browser
For instance, if you forget to add a semicolon at the end of a JavaScript statement, ESLint will
report this as a problem.
These problems don’t stop the code from running. However, they don’t adopt certain code
styling conventions for readability, and maintenance of the code, either.
21
22
ESLint is highly flexible and configurable. Every aspect can be adapted to fit a project’s needs.
In addition, you can write your own ESLint rules, and use hundreds of ready-made rules.
Prettier, on the other hand, is an opinionated code formatter. When it runs, it formats your code
with proper spacing and indentations.
ESLint and Prettier integrate together, so Prettier problems can be reported as ESLine
problems.
When we created our first Vue.js app before, we picked E SLint + Prettier as our linters for
the app. Vue.js has its own set of ESLint rules already baked into the Vue CLI.
Let’s see what the CLI has created for us with regard to ESLint and Prettier.
Locate the .eslintrc.js file at the root of the app folder. This file contains the ESLint and Prettier
configuration settings for this app.
22
23
This configuration file includes a set of ESLint plugins. Typically, every plugin contains a defined
set of ESLint custom rules to apply to JavaScript files, or any other file extension.
vue/prettier plugin is the ESLint plugin for Prettier formatting for Vue Single
Finally, the @
File Components(SFC).
23
24
ESLint is highly configurable and accommodates the needs of any app. By default, the ESLint
parser is compatible with ECMAScript 5 syntax. However, Vue.js components, and objects, are
abel-eslint as the default parser for this app.
written with Babel. Therefore, it adds the b
VS Code integration
ESLint and Prettier both run, and report results, on the command line / terminal. Therefore, to let
VS Code know about their results, we need to install two more VS Code extensions.
Open VS Code, and locate the Extensions page. Search for both ESLint, and Prettier
extensions, and install them.
While inside VS Code, go to Preferences, and then click Settings. Make sure you select the
Workspace tab, and click the Open Settings(JSON) button located at the top right side.
- ditor.formatOnSave setting
Disable the e
- ditor.codeActionsOnSave. Formatting
Allow ESLint to auto fix any errors on e
usually relates to inserting and removing whitespace, while a source code action
removes unnecessary imports, unused variables, etc.
24
25
You have just integrated ESLint and Prettier with VS Code. Start enjoying an incredible
experience of allowing VS Code to lint and format your code automatically!
With a SCRM system in place, you and your team members can all share access to the app
source code at any time you wish.
For example, my colleagues and I might add or modify code, and push the changes to the
centralized repository. That way, developers joining the team will clone the centralized
up-to-date repository, and can start coding instantaneously.
A SCRM also contains best practices and workflows. For instance, Figure 15 depicts the
workflow of implementing a new feature in your application.
aster, or d
Start by cloning or branching to the m ev, branch.
1. Create a new branch name relevant to the feature you are adding.
a. Add your code, and commit the changes locally.
25
26
b. Push the local branch to a SCRM system- GitHub for instance.
2. Create a Pull Request based on the new branch, and invite your team members to
review and comment.
aster, or d
5. The team Approves & Merges PR into either the m ev, branch on your repo.
The above is a typical SCRM Workflow that I use on a daily basis. It’s quite simple, and straight
to the point, yet organizes the development process with all team members without losing code,
or overlapping.
Learning Git
Git (https://git-scm.com/) is at the core of learning and using a SCRM system. It’s an open
source distributed version control system. GitHub and friends are all based on Git. They only
differ in the User Interface, capabilities and services, and, of course, pricing. Once you learn Git,
you can use any of these SCRM systems. There are many resources to help you learn Git.
However, here’s a set of resources I’ve used before:
- Git tutorial
(https://www.youtube.com/playlist?list=PL3Sf6euafegw5C-V4zMCmsVl7GjiXNV0E). This
tutorial vividly illustrates the concept of Git Rebase, a Git feature I use daily.
26
27
Push your code to GitHub
Vue CLI automatically initializes a new repository upon a new app’s creation. It automatically
detects that Git is locally installed on the computer, and initializes a local Git repository.
To prove that, navigate to the app root folder, open a Command Line / Terminal, and run the
following command:
The message says you are on m aster branch, and nothing to commit. In other words, you
haven’t changed anything that Git needs to track.
Let’s go to Github, and create a new repository. If you don’t have an account on GitHub, you
need to register first.
First, login to GitHub, and then navigate to creating a new repository (https://github.com/new).
Fill in the details of the new GitHub repository as shown in Figure 16:
27
28
Figure 16: Create a new GitHub repository
Click the Create repository button. GitHub allows the creation of either public or private
repositories.
GitHub then takes you to the repository info page as shown in Figure 17:
28
29
Figure 17: GitHub repository home page
To connect your local Git repository to the GitHub repository, you need to follow one of these
two guidelines:
If you haven’t yet created your local Git repository, then you need to follow the steps below:
29
30
If you have created a local Git repository (which is our case now), you need to follow the steps:
Switch back to the Vue app, navigate to the app root folder, open a Command Line / Terminal,
and run the following command:
Now, you can go to another computer, pull down the repository, and start working on it.
With every new feature you build into your app, follow the Git Workflow explained above to deal
with Git and GitHub.
30
31
and desktop devices. In addition to that, one must write CSS to run across multiple and different
browsers, hence maintaining cross-browser compatibility is the hardest by far.
That’s why CSS frameworks like Bootstrap, Tailwind, and the like, have emerged to help
developers build rich, adaptive, cross-browser User Interfaces more quickly. In this guide, I will
focus on Bootstrap and Tailwind only.
Bootstrap is, by far, the most popular HTML, CSS, and JS framework for developing responsive,
mobile-first projects on the web. Tailwind is different from Bootstrap in that it's not a UI kit.
Instead, it’s a utility-first CSS framework for rapidly building custom designs. It doesn't have a
default theme, and there are no built-in UI components. It comes with a set of predesigned
widgets with which to build your site.
Bootstrap is a more opinionated framework than Tailwind. The major differences between the
two are:
- Preprocessors: Bootstrap ships with both vanilla CSS, and the source code that’s built in
CSS preprocessors, and Sass. You can use the precompiled CSS right away, or build on
the source.
- One framework, every device: Bootstrap is well-known for making your website adaptive,
and cross-browser, with a single code base, using CSS media queries. Bootstrap is well
known for the Grid system to build layouts.
- Full of features: Bootstrap offers extensive, and beautiful documentation for common
HTML elements, dozens of custom HTML and CSS components, and awesome jQuery
plugins.
On the other hand, Tailwind CSS provides low-level utility classes that let you build completely
custom designs. It’s way different from Bootstrap in terms of providing:
- No default theme
- No built-in UI components
Now that you know what both frameworks can offer you, I will leave it up to you to choose which
one with which to work. However, I will show you how you can configure both frameworks in
your Vue app.
31
32
Using Bootstrap
You can find the source code used in this section under the Git branch named using-bootstrap.
If you are going to use the Bootstrap styles only, then run the following command:
If you want to use Bootstrap’s built-in UI components, then you need to install two more NPM
packages.
The jQuery, and Popper.js packages, are required for the UI components to function properly.
Next, open the src\main.js file in your Vue app, and add the following line of code:
If you want to use Bootstrap’s built-in UI components, then you need to add an additional line of
code:
That’s all! Now you can start Bootstrap in your Vue app.
32
33
Using Tailwind
You can find the source code used in this section under the Git branch named using-tailwind.
Tailwind is packaged as a PostCSS plugin. To start using it in your Vue app, you first need to
install the plugin, and then instruct Vue to use this plugin.
In brief, PostCSS transforms the CSS you write in your app into a CSS that browsers can
understand, using JavaScript plugins.
One of the most popular PostCSS plugins is the CSSNext (https://cssnext.github.io/). It helps
you use the latest CSS syntax today. It transforms new CSS specs
(https://www.xanthir.com/b4Ko0) into more compatible CSS so you don't need to wait for
browser support.
The Vue CLI uses Webpack under the hood to bundle your app, and make it browser-ready. In
order for Webpack to load the Vue components, the Vue CLI team created the official Webpack
loader for Vue.js components Vue Loader (https://github.com/vuejs/vue-loader).
Internally, the Vue Loader makes use of PostCSS. Therefore, we can easily install, and use,
Tailwind in our app by following the steps.
Now, add a postcss.config.js JavaScript file to the root folder of your app, and paste this
content:
33
34
We are adding Tailwind as a PostCSS plugin. We are also adding the Autoprefixer
(https://github.com/postcss/autoprefixer) PostCSS plugin. This plugin automatically adds vendor
prefixes to your CSS. Tailwind doesn’t have any autoprefixer backed inside, so we need to add
the Autoprefixer plugin.
By adding these two plugins, we are telling PostCSS to apply these plugins to our CSS. More
specifically, the Tailwind PostCSS plugin will locate Tailwind directives, and process them as
you will see shortly.
Our next step is to add Tailwind to our CSS. Inside the path src\assets, create a new CSS file
named styles.css inside a new folder named styles. Inside this file, use the @
tailwind directive
to inject Tailwind's base, components, and utilities styles, into your CSS:
Tailwind will swap these directives out at build time with all of its generated CSS.
The final step, before you are able to use Tailwind, is to import the CSS file above into the
src/main.js file as follows:
That’s it! Now you can enjoy using Tailwind in your app.
A UI Component library follows the same trend, and offers its developers a wide range of
building blocks. They include buttons, input elements, scrolling lists, calendars, and grids, to
34
35
mention just a few. They are built in such a way that you can easily install them in your app to
start using them right away.
We have seen how you can integrate Bootstrap and Tailwind in your Vue app. These
frameworks work well, and are great. However, they behave as an external layer on top of
Vue.js, rather than being baked into Vue.js context, and environment. You’ve got to do a fair
amount of work to integrate Bootstrap’s components into Vue.js context.
That’s why Vue-based UI Component libraries exist! These libraries offer a set of UI
Components that you can use to build the User Interface or UI of your app. They are built as
Vue.js Components, so they effortlessly slide into your app. They make development faster, and
more consistent!
In this section, I will show you how you can integrate two well-known, and proven Vue.js UI
Component libraries into your app.
Let’s see how you can install this library, and start using it in your Vue.js app.
You can find the source code used in this section under the Git branch named add-vuetify
(https://github.com/bhaidar/vue-first-app/tree/add-vuetify).
Navigate to your app root folder, and run the following command:
You can read more about Vue CLI Plugins using this link:
https://cli.vuejs.org/guide/plugins-and-presets.html
Once the installation is done, you are prompted to install a Veutify Preset.
35
36
A preset is a bunch of styles and components to get you started, and demonstrates how to use
Veutify in your app.
nter.
Let’s keep the default selection, and hit E
The new plugin installed adjusts your app by creating a new src/plugins folder. In addition, it
creates the veutify.js plugin file inside the folder with the following content:
36
37
You can see how the Veutify plugin is imported to the main Vue instance.
Switch back to the src/App.vue component, and notice how its content was replaced by
installing the Veutify default preset:
37
38
With Veutify, you have a bunch of Vue.js Components that you can make use of inside the
Vue.js templates.
For a complete list of Veutify components, I suggest going through their API Explorer
(https://vuetifyjs.com/en/components/api-explorer/), and checking all of them.
Bootstrap Vue
This is the Vue.js version of Bootstrap. You already have an idea of what Bootstrap is, and what
it can provide. BootstrapVue comes with over 40 plugins, more than 80 custom components,
and over 300 icons. It provides one of the most comprehensive implementations of Bootstrap v4
components, and grid system, for Vue.js.
Let’s see how you can install this library, and start using it in your Vue.js app.
You can find the source code used in this section under the Git branch named add-bootstrapvue
(https://github.com/bhaidar/vue-first-app/tree/add-bootstrapvue).
Navigate to your app root folder, and run the following command:
and hit E
Enter the letter Y nter.The installation continues.
38
39
The new plugin installed adjusts your app by creating a new src/plugins folder. In addition, it
creates the bootstrap-vue.js plugin file inside the folder with the following content:
The BootstrapVue plugin is imported together with all of the supporting imports needed.
39
40
b-alert> component displays an alert on the page as shown in Figure 18:
The <
BootstrapVue provides many more Vue components that you can use in your app. Check the
entire suite of Components (https://bootstrap-vue.js.org/docs/components/) on their website.
40
41
Section 9: Third-party Vue.js Modules
The Vue.js core framework can help you begin developing apps right away. However, once you
add more features, more pages, and begin consuming data from remote Web APIs, your app
gets bigger. You need to look for third-party modules to help you get your work done following
well known standards, best practices, and above all, excellent testing methods! Don’t reinvent
the wheel!
Here, we will discover a few modules that are in any Vue.js app. Of course, there are tons of
them out there that might be more specific, or what simply target certain aspects of an app.
Axios
Axios (https://github.com/axios/axios) is a Promise-based HTTP Client for the browser, and
Node.js. It offers the following features:
1. Makes XMLHttpRequests
(https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser.
6. Cancels requests.
Vue.js doesn’t ship with a library to perform HTTP requests out of the box. Therefore, we need
to use a third-party module to help us with that.
One of the options is to use Axios. There is another module that I won’t be detailing here, but in
case you want to learn more about it, it’s the Vue-Resource
41
42
(https://github.com/pagekit/vue-resource) module. Personally, I prefer using Axios, especially
when I can use the same library with Vue.js, and Node.js.
To start using Axios in your Vue.js app, install the Axios NPM package by running the
command:
Then, in order to use Axios to communicate with a remote Web API, you use one of the many
reated()
functions available on Axios. Typically, you query for remote data inside the c
life-cycle hook in Vue.js component:
Axios exposes more functionality. For instance, the a xios.post() is used to post data to the
server. You can play with a full list of functions available in Axios by checking Axios examples
(https://github.com/axios/axios/blob/master/examples/README.md).
That was just an introduction to using Axios in a Vue app. I recommend reading the following
article to gain more knowledge about Axios: Vue.js REST API Consumption with Axios
(https://alligator.io/vuejs/rest-api-axios/).
42
43
Vue Router
Client-side routing is at the core of Single Page Apps (SPA). With routing, you can navigate to
other screens, or pages, without reloading the entire page.
Vue Router (https://router.vuejs.org/) is the official router for Vue.js. It deeply integrates with
Vue.js core to make building SPAs with Vue.js a breeze. The features include:
The Vue.js team provides extensive support and documentation on Vue Router. It’s the most
useful resource to learn about Vue Router, and explore its API.
There are hundreds of examples that you can explore in order to deepen your understanding.
You can access them by following this link:
https://github.com/vuejs/vue-router/tree/dev/examples.
Back in Section #4: Vue CLI, we added the option to install Vue Router while creating a new
Vue.js app. Let’s see how the Vue Router is enabled, and installed, in the app.
43
44
Locate the src/router/index.js file content:
The code installs Vue Router as a Vue Plugin. Then, it defines a set of routes to be used by Vue
Router. You should customize, add, and remove routes as per your app. Finally, the code
ueRouter object with the routes defined. The V
creates a new instance of the V ueRouter
instance is exported at the end of the file.
44
45
ueRouter instance to the
To make the Vue app aware of the routes, you need to pass the V
main Vue object representing your app.
To start using it, you will need to be aware of two major components:
- RouterView (https://router.vuejs.org/api/#router-view)
- RouterLink (https://router.vuejs.org/api/#router-link)
The R outerView component is a placeholder that you add to indicate, to the Vue Router
plugin, where to load components to which the user is navigating.
outerLink component is used to link to one of the predefined routes in the app.
The R
That’s all! Make sure to read the documentation to grasp the ins and outs of the Vue Router.
Vuex
Vuex (https://vuex.vuejs.org/) is a state management library for Vue.js. It serves as a single
source of truth for any managed state in your app. It stores the state of all the components in
your app in a centralized store. Components can communicate with the store to either update
the state, or read it.
The ultimate goal of Vuex is to control mutating the state of your app. With Vuex, mutating the
state becomes predictable and regulated. This gives way to a conceptual pattern that’s more
ne-way-data-flow. This pattern is illustrated in Figure 19:
popular in SPAs, which is the o
45
46
Figure 19: Vuex - one way data flow
2. The Action communicates with a remote Web API. It then commits the results into a
Vuex Mutation. A Vuex Action is not allowed to mutate the state. It does so by means of
a Vuex Mutation.
3. The Mutation mutates the Vuex Store’s State object. The State is shared across all
components in a Vue app.
4. The State is now mutated. Vuex triggers the Vuex Reactive Getters to read fresh data
from the State.
5. The Vue engine detects a change in the value of the Vuex Getters; it renders the new
data, and refreshes the affected components.
46
47
This is just a brief explanation of how one-way-data-flow occurs inside a Vue app.
The team behind Vuex did a great job in offering well-structured, and detailed documentation, to
explain the intrinsic aspects of Vuex. Make sure you read the Vuex documentation
(https://vuex.vuejs.org/guide/).
Back in Section #4: Vue CLI, we added the option to install Vuex while creating a new Vue.js
app. Let’s look at how the Vuex is enabled, and installed, in the app.
uex.Store object.
This code installs Vuex as a Vue Plugin. Then, it creates a new instance of V
- State: This object holds all the state elements managed by the store.
- Mutations: This object holds all the mutation functions available by the store.
- Actions: This object holds all the action functions available by the store.
- Modules: This object holds all the different modules created as part of the store. You can
layout and structure your store by means of independent modules. That’s an advanced
topic, and I suggest consulting with the Vuex documentation
(https://vuex.vuejs.org/guide/modules.html) to learn more about Vuex Modules.
47
48
Switch back to the src/main.js file, and notice the following:
uex.Store instance to
To make the Vue app aware of the Vuex store, you need to pass the V
the main Vue object, representing your app.
Vuelidate
Form validation is an essential task you carry on in each and every Web app. In principle, you
cannot trust your users and you’ve got to protect your app by validating whatever input you
receive from them. It has always been advisable to perform data validation on the client-side
and the server-side. Since we are talking about Vue.js, let’s focus our attention on client-side
validation. This however, doesn’t mean server-side validation is not important!
1. To handle the validation manually and that’s doable, but might become troublesome with
time especially when the forms become bigger and more involved in terms of validation
logic.
2. To make use of a third-party validation library that could take this burden off your hands
and replace the manual validation with a more systematic and robust one.
- Model based
- Decoupled from templates
- Dependency free minimalistic library
- Support for collection validations
- Support for nested models
48
49
- Contextified validators
- Support for function composition
- Validates different data sources: Vuex getters, computed values, etc.
- High test coverage
Before we dive into this library, let me demonstrate how to manually validate a form in Vue.js
and then switch to Vuelidate.
You can find the source code used in this section under the Git branch named add-validation
(https://github.com/bhaidar/vue-first-app/tree/add-validation).
49
50
Figure 20: Form Validation
The Form has three fields. Below is the HTML template for this Form:
50
51
ovalidation=”true” on
Notice how we disable the default HTML Form validation by setting n
the Form element.
ave() function.
Let’s submit the Form and go over the s
51
52
The function uses basic conditional statements to check for the existence of a value for the
Name and E mail fields. It checks if the email entered is a valid email. While doing so, it
populates an array of errors that is eventually displayed for the user in case there are invalid
fields. Figure 21 shows those errors.
52
53
Figure 21: Form with errors
That’s it!
For a complete reference on native Form validation in Vue.js make sure you read the
documentation (https://vuejs.org/v2/cookbook/form-validation.html).
You can find the source code used in this section under the Git branch named add-vuelidate
(https://github.com/bhaidar/vue-first-app/tree/add-vuelidate).
53
54
Run the following command to install the Vuelidate NPM package
(https://www.npmjs.com/package/vuelidate) into your app:
Vuelidate is a Vue.js Plugin. To add it into the app, locate the src/main.js file and replace its
content with the script below:
ue.use() function.
To install a Vue.js Plugin we make use of V
54
55
equired, m
We start by importing the Vueldate built-in validator mainly the r inLength, and
email validators.
For a complete list of validators make sure to visit the Vuelidate Builtin Validators
(https://vuelidate.js.org/#sub-builtin-validators).
Vuelidate integrates tightly with the Vue.js Options API. It adds a new property named
validations. It’s there, you define your validations.
55
56
ame field required with a minimum length of 4
For instance, the code above makes the n
mail field is made a required one and accepts only valid email addresses.
characters. The e
ubmitted to t
1. It sets s rue meaning that the Form is now submitted.
his.$v.$touch() method, defined by
2. It triggers the Form validation by calling t
Vuelidate.
his.$v.invalid property, defined by
3. The result of validation is saved inside t
Vuelidate. If the Form is invalid, the method returns and errors are now displayed for the
user. Otherwise, it continues normal processing.
56
57
This is the same HTML Form we used previously however, I removed the errors section and
added error handling under each field to be validated.
For example, the “Name is Required” error message is shown only when the field is required,
it’s value is empty and the Form is submitted.
57
58
Vuelidate attaches the validation information on a field and allows you to access them via
$v.name.required, or $ v.email.required, or $ v.email.email, etc.
Now let’s submit the Form without filling any information and see how the error messages are
displayed under the field. Figure 22 will demonstrate this.
The error messages start to disappear when you fill in the fields with valid data.
Simple really.
58
59
I’ve only scratched the surface when using Vuelidate in a Vue.js app. This library has a rich set
of features and I highly recommend going through their documentation website to learn more.
(https://vuelidate.js.org/#examples)
Vue-i18n
Internationalization and localization of an app, in general, is a difficult task. It entails many
aspects starting with localizing content to be displayed on the Web app, localizing routes,
handling document language and layout direction Right To Left (RTL) and Left To Right (LTR),
deciding on the database structure for localized data and many other facts.
You can find the source code used in this section under the Git branch named add-i18n
(https://github.com/bhaidar/vue-first-app/tree/add-i18n).
The command downloads and installs the Vue-i18n library. During installation you are prompted
to answer a few questions to install and customize the plugin the correct way. The questions are
shown in Figure 23.
In addition to installing the Vue-i18n plugin, the command does a few things behind the scenes
mainly to do with the configuration and to make the plugin ready to use without any additional
effort on your part. I won’t go into the details but I will recommend a great resource for this.
59
60
The Ultimate Guide to Vue Localization with Vue I18n
(https://phrase.com/blog/posts/ultimate-guide-to-vue-localization-with-vue-i18n). This is by far
the most comprehensive and current tutorial online for the Vue-i18n plugin.
For now, locate the src/locales/en.json file. This was added by the plugin installation process.
This file will eventually contain all localization messages for the English language in this app.
With this:
I’ve only just touched on using Vue-i18n in a Vue.js app. This library has much more to offer on
this subject and I recommend going through their documentation website to learn more.
(https://kazupon.github.io/vue-i18n/started.html).
60
61
Vue Apollo
“GraphQL is a query language for APIs and a runtime for fulfilling those queries with your
existing data. It provides a complete and coherent description of the data in your API, gives
clients the power to ask for exactly what they need and nothing more, makes it easier to evolve
APIs over time, and enables powerful developer tools.”
If you are planning to use GraphQL in your Vue app, you should be checking the Vue Apollo
(https://vue-apollo.netlify.com/) Plugin. It integrates Apollo (https://www.apollographql.com/) into
your Vue app.
Apollo is a GraphQL implementation standard for the client-side, and server-side. You can
implement GraphQL on the backend/server using Apollo Server
(https://www.apollographql.com/docs/apollo-server/). On the client-side (React, Vue, or
Angular), you can use Apollo Client (https://www.apollographql.com/docs/react/) to
communicate with the Apollo Server.
To install Vue Apollo, check this detailed guide on how to do so: Vue Apollo Installation
(https://vue-apollo.netlify.com/guide/installation.html#_1-apollo-client).
To start using Vue Apollo in your Vue app, check this detailed guide: Using Vue Apollo
(https://vue-apollo.netlify.com/guide/apollo/#apollo-options).
Following this trend, several libraries emerged to help document, and test, components. For
instance, Storybook (https://storybook.js.org/), a library that is used with React.js, Vue.js and
Angular frameworks. With Storybook, you build your UI components, and then write Storybook
stories to consume those components. Think of it as doing Component Unit Testing. An
example of a Storybook story is shown below:
61
62
Given a B utton component, the story renders three instances of this component, each time
with different text content.
Storybook reads all stories in your application, and renders them inside the browser outside the
context of the application. This means that you can have team one working on the components
in a separate project, and have another team building the pages, and consuming the
components.
In addition to having the ability to view all your basic components in a Component Explorer, you
are also indirectly testing your components via Storybook stories. Each and every store
represents a single state of a component. You will write stories for basic components, and also
stories for composite components, hence the ability to test your components outside the app
context.
Install Storybook
Let’s add Storybook to our Vue.js app by following the steps below. You can find the source
code used in this section under the Git branch named add-storybook.
We need to install further NPM packages to let Storybook load our Vue.js components, and all
the SCSS inside these components. Run the following command:
62
63
Once all the packages are installed, create a new .storybook folder at the root folder of the app.
Note the dot before the name of the folder.
With this, you are instructing Storybook to load all story files with names, ending in .stories.js,
from within the src/stories folder.
Then, create a new src/stories folder. This folder holds all the Storybook stories in your app.
Back in Section #4: Vue CLI, we added the option to use SCSS while creating a new Vue.js
app. Therefore, we need to instruct Storybook to load any SCSS code it finds in our Vue.js
components. To do this is, we will create a .storybook/webpack.config.js JavaScript file, and will
add the following content:
63
64
The file instructs Webpack to deal with any file that ends with an extension of .scss and <
style
lang="scss"> blocks in .vue files. For these files and blocks, Webpack will use three loaders,
ue-style-loader, then c
starting with v ss-loader, and finally the s
ass-loader.
Now our Vue.js components will render perfectly inside the Storybook stories.
64
65
The story:
- elloWorld component.
Imports the H
Before we can actually run this story, open the package.json file at the root of the app folder.
Add the following convenient script to run Storybook in your app:
65
66
A new browser opens and shows all the stories defined in the app as shown in Figure 24:
66
67
Then, install the Storybook addons NPM packages:
After that, create a new file inside .storybook/addons.js with the content:
toryRouter
Finally, adjust the Storybook story to load the S
(https://github.com/gvaldambrini/storybook-router) object via Storybook decorators
toryRouter allows you to use
(https://storybook.js.org/docs/addons/introduction/). The S
routing-aware components in your stories.
That’s it!
67
68
How to use Vuex inside a Storybook story
Storybook stories want to render components that make use of Vuex. How do you integrate
Vuex with Storybook? That’s very simple!
Locate, and open the .storybook/config.js file, and add the following:
ue and V
You just import V uex objects, then add the Vuex plugin to the Vue instance. You can
dispatch store actions, or commit store mutations from within the config file. Most of the time, I
find myself committing mutations with hardcoded data to test my components. Nothing new
here! You are populating the store with some data to be used later when the Storybook stories
load.
68
69
elloWorld component uses the Vuex store, it will run smoothly, without any
That’s all! If the H
issues, inside Storybook runner.
If you are using the Bootstrap library in your app, you can import the bootstrap.scss file into the
.storybook/config.js as follows:
You may use the preview-head.html file to include additional stuff to render together with the
Storybook stories.
Including Tailwind (https://tailwindcss.com/) is a little bit more involved. Either you use the
prev-head.html, and include the Tailwind on CDN
69
70
(https://tailwindcss.com/docs/installation/#using-tailwind-via-cdn) option, or you use a more
advanced technique that involves Webpack. Here are two resources that will help you do so:
- Tailwind-storybook
(https://github.com/audunru/tailwind-storybook/blob/master/.storybook/webpack.config.j)
70
71
Section 12: Testing Vue apps
Software testing has become an integral part of every software development methodology.
Testing your code guarantees a high level of confidence in the apps you are delivering to your
clients.
In this section, I will introduce the different types of software testing, and then explore the
different testing options for Vue.js apps.
Testing types
Figure 25 shows the traditional Software Testing Pyramid, and the different types of testing
available through the development life cycle.
71
72
Unit Testing
Unit testing is a method that looks at individual units of code. It’s a crucial part of Continuous
Integration (CI) (https://codeship.com/continuous-integration-essentials). It isolates individual
functions to check inputs against outputs, making sure each part of the software functions as
expected.
Integration Testing
While unit testing focuses on individual functions in the source code, integration testing
(http://softwaretestingfundamentals.com/integration-testing/) is done on a higher level of
abstraction. Integration testing checks the communication between:
End-to-End Testing
Functional testing- also known as End-to-End or E2E testing- sits at the top of the pyramid.
When writing a functional test script, you focus on testing the logic of the application, as well as
verifying, and implementing, all the features requested by your client. Functional testing usually
follows a scenario testing path, taken in your application, starting from a certain point, and
ending at another point. For instance, a possible functional test could test the entire Login
process:
- If the credentials are correct, the user is redirected to the secure access pages.
- Otherwise, the user is denied access, and is left with an error message stating a
possible reason for the login failure.
Only when the test runs, and succeeds, will you have verified, and fulfilled one functional
requirement, requested by your client. Then, you move on to write the next tests.
72
73
Visual Testing
With the way technology is evolving, the need for visual testing has never been stronger. It's
unacceptable to have any type of bug in your application. The general public is unforgiving. This
challenge is growing exponentially with the constant introduction of new devices, operating
systems, browsers, and screen resolutions.
With unit, integration, and functional testing, you can obtain a certain level of confidence in the
function of the application, and to what extent it serves its purpose. However, with visual testing,
you can be sure your application works across all platforms without any hiccups. If your apps
run smoothly on all platforms, you should expect consumer confidence.
The special relationship between functional and visual testing distinguishes the two among all
forms of testing. Functional testing has been around for a long time. It’s reputable, and the
testing frameworks supporting functional testing are robust.
Visual testing takes advantage of existing functional testing infrastructure and builds its tools on
top of it. Given a functional test, you can easily integrate a visual testing framework by injecting
function calls inside of your tests. These function calls serve the purpose of taking snapshots,
sending them to the backend servers for analysis and comparison, and finally, generating a
report of the results.
If you are interested in learning about visual testing, I’ve written thirteen articles
(https://applitools.com/blog/author/bilalhaidar) exploring Applitools as a visual testing
framework.
All of the above testing types come in the form of automated tests. By leveraging them, you
benefit from using regression testing to ensure the validity of your app at all levels.
You can find the source code, used in this section, under the Git branch named “add-tests”
(https://github.com/bhaidar/vue-first-app/tree/add-tests).
73
74
In brief, the Vue Test Utils library offers the following features:
- It tests Vue components by mounting them in isolation, mocking the necessary inputs
(props, injections and user events), and asserting the outputs (render result, emitted
custom events).
- Simulates User Interaction by allowing you to trigger a Button inside the component
under test.
To learn how to do unit testing in your Vue.js app, I suggest reading the three articles, provided
in the links, to gain a greater understanding of what must be tested, and how.
While creating a new Vue.js app back in Section #4: Vue CLI, we added the option to use unit
testing in the sample app, and also made use of Jest (https://jestjs.io/), a well-established
JavaScript testing framework with so many goodies. The Vue CLI adds all the necessary bits to
allow writing, and running, unit tests in the app.
Each component you want to test should have a corresponding spec file that represents the test
suite of a component. The spec file is named after the component name. For instance, a
component named N avigation will have a corresponding spec file named navigation.spec.js.
The spec file should be placed under the tests/unit folder in your app as well.
Switch back to the Vue.js app, and checkout the Git branch named add-tests
(https://github.com/bhaidar/vue-first-app/tree/add-tests).
74
75
Locate the tests/unit/counter.spec.js file. It’s a basic test suite with two tests, written as follows:
75
76
To run all unit test scripts in your app, run the following command:
The tests are run, and results are displayed on the screen as shown in Figure 26.
Using s hallowMount(), which is provided by the Vue Test Utils, is essential to writing this
test. This method allows you to create an isolated instance of the component without loading its
children.
End-to-End Testing
Whether the app is written in Vue.js, or some other framework, functional, or E2E, testing works
the same.
While creating a new Vue.js app back in Section #4: Vue CLI, we added the option to use
Cypress (https://www.cypress.io/) as an E2E testing solution. The other option was Nightwatch
(https://nightwatchjs.org/), which I won’t cover in this guide. However, I’ll include some
recommended resources for you.
Before you can start writing functional tests, I suggest reading or watching the following
resources in order:
1. Introduction to Cypress
(https://testautomationu.applitools.com/cypress-tutorial/?utm_term=&utm_source=web-r
76
77
eferral&utm_medium=blog&utm_content=blog&utm_campaign=&utm_subgroup=): a
free and detailed video course for beginners by Gil Tayar.
2. Cypress Tutorial for Beginners: Getting started with End to End Testing
(https://www.valentinog.com/blog/cypress/): An informative article on E2E testing in
Cypress.
Now, going back to the Vue.js app, checkout the Git branch named add-tests
(https://github.com/bhaidar/vue-first-app/tree/add-tests).
Locate the tests/e2e folder. This folder represents the Cypress setup folders that the Vue CLI
scaffolds for us while creating the Vue.js app. You will place all of your E2E spec files inside the
tests/e2e/s pecs folder.
For now, let’s explore the single spec file named test.js, as shown in Figure 27.
77
78
Figure 27: Cypress E2E test script
Although basic, this example is enough to help us understand how to write Cypress E2E tests,
and run them inside of a Vue.js app.
1. Navigates the browser to the root page of the currently running app
Cypress gives you the chance to go crazy, and query the underlying DOM, or simulate user
interactions like filling an input field, or clicking a button, as well as many other techniques
(https://docs.cypress.io/guides/core-concepts/introduction-to-cypress.html).
To run all e2e test scripts in your app, run the command:
78
79
This command internally runs the Cypress command behind the scenes. Figure 28 shows the
Cypress test runner app open for the first time.
Since we are running the test runner for the first time, you receive a message notification saying
that Cypress plugin has added a few sample tests for your reference to help you get started.
Close the popup window to access the single E2E test in our app, as shown in Figure 29.
79
80
Figure 29: E2E tests listing
Locate the single test.js test script, and click on it. Cypress will launch a new instance of a
Google Chrome browser, and will run the clicked test script.
Figure 30 shows the full steps performed to run the single E2E test script in hand.
80
81
Figure 30: Full E2E test script run
The left side displays all of the steps/actions you’ve specified when writing the test script. On the
right side, you see the result of executing the steps/actions of the test script.
This is just the tip of the iceberg for writing E2E test scripts. The resources I shared with you are
enough to get you started writing functional/E2E tests for your Vue.js apps.
Visual Testing
Visual testing is one of my favorite testing topics. The beauty of it is in the ability to catch any
single change in the HTML and CSS code, that even the naked eye cannot see.
To start using Visual testing in your app, you need to use a framework, such as Applitools
(https://applitools.com/), or Percy (https://percy.io/). I will call on Applitools for this guide.
With Applitools, you can introduce visual testing into your app by means of two methods:
1. Start by writing E2E tests with Cypress, and then upgrade the E2E tests to visual tests.
I’ve written about this method here: How to visually test VueJS apps using Cypress.io
and Applitools (https://applitools.com/blog/test-vuejs-cypress-io-applitools).
81
82
2. If you are using Storybook in your app, then you can test the stories with visual testing.
I’ve written about this method here: Visually Test Vue.js application using Applitools and
Storybook (https://applitools.com/blog/visually-test-javascript-vue-storybook-applitools).
I won’t delve into any more detail, but the two articles quoted are more than enough to get you
started.
When employing CI in your development workflow, creating a new PR in your SCRM system
triggers the CI workflow via a webhook more often than not.
82
83
1. Create a new branch name, relevant to the feature you are adding.
a. Add your code, and commit the changes locally.
b. Push the local branch to a SCRM system- GitHub, for instance.
2. Create a Pull Request based on the new branch, and invite team members to review,
and comment. In parallel, the SCRM triggers the CI Service.
3. The CI Service:
a. Pulls the branch with PR.
b. Builds the branch.
c. Runs the tests, such as unit tests, e2e, and visual tests.
4. The CI Service reports the results of building the app, and running the tests, back to the
SCRM.
If the CI Service reports errors, the PR is not merged. The developer is required to fix any
issues, and push the branch again. Otherwise, the PR is approved, and is ready to be merged.
- Jenkins (https://jenkins.io/)
- Travis CI (https://travis-ci.com/)
- Google CI (https://cloud.google.com/solutions/continuous-integration)
The process of connecting a SCRM to a CI Service is lengthy and detailed. Therefore, I will
direct you to a few resources to get started with CI, and how to add CI to your Vue.js app.
83
84
2. Deploying Vue with CircleCI 2.0
(https://rossta.net/blog/deploying-vue-with-circleci-2.html). This short article assumes a
fair bit of knowledge about CircleCI, and demonstrates a practical example of using
Vue.js and CircleCi.
Now, let’s take a quick look into the future with Vue 3.
Bonus: Vue 3
A guide on learning Vue wouldn’t be complete without mentioning Vue 3! Its release has been
set for later this year (2020).
To stay updated on upcoming Vue 3 news, you can refer to this blog link: Vue 3 – A roundup of
infos about the new version of Vue.js (https://madewithvuejs.com/blog/vue-3-roundup).
Vue features, and enhancements, are driven by two factors: The Vue Core team, and The
Community! If you follow the Vue RFC (https://github.com/vuejs/rfcs) GitHub repository, you can
see a list of the Request For Comments (RFC) the Vue Core team is proposing for inclusion in
the upcoming release. They are inviting developers all over the world to participate by
commenting, and discussing, the RFC before they make final decisions on any new
implementations that go out for shipping in the framework.
The Vue 3 features coming are non-breaking changes from the perspective of a developer. The
syntax you use for Vue 2 can be applied to building Vue 3 apps, with no major changes to note.
The major shift apparent in Vue 3 is found within the internal framework. Here is where the bulk
of the changes have been made.
You can start using, and exploring, Vue 3 features thanks to the Vue CLI Plugin for Vue Next
(https://github.com/vuejs/vue-cli-plugin-vue-next?ref=madewithvuejs.com). To use this plugin,
start by creating a new Vue app with the existing Vue CLI (Refer to Section 4 on creating Vue
apps).
84
85
To install the Vue CLI Vue Next plugin, run this command inside your app:
- Configures webpack to compile .vue files with the new Vue 3 compiler.
- A simple codemod that automatically migrates some global API changes mentioned in
RFC#0009 - Global API Change
(https://github.com/vuejs/rfcs/blob/master/active-rfcs/0009-global-api-change.md).
Here’s the lowdown on a few of the new features with the relevant links to help get you more
informed.
By using named exports, and with the help of Webpack 4 Tree Shaking
(https://webpack.js.org/guides/tree-shaking/), the Vue runtime can do the tree-shaking to
eliminate any non-reachable, or dead code, to minimize the size of the final package.
85
86
Global API Changes
This feature is illustrated in this RFC: RFC#0009 Global API Change
(https://github.com/vuejs/rfcs/blob/master/active-rfcs/0009-global-api-change.md).
This change affects bootstrapping a Vue app. The intention of this change is to minimize
cluttering the main Vue instance by shifting registering global stuff on the main Vue instance to
seperate app instances. Currently, Vue 2 doesn’t have the concept of an app. For example, you
register global mixins (https://vuejs.org/v2/guide/mixins.html) or global components on the main
Vue instance. Basically, if you want to serve two apps, both will share the same global settings.
86
87
reateApp from the v
You import a new function named c ue package. Then, you use this
pp by passing a root component.
function to create a new application named a
This way, you can create multiple Vue apps following this technique.
Another benefit of this change is to isolate Vue Tests in your app without cluttering them with
any pre-configured stuff.
Make sure to read the RFC referenced above for a more detailed explanation on the motives
behind this change.
Composition API
This feature is illustrated in this RFC: RFC#00013 Composition API
(https://github.com/vuejs/rfcs/blob/master/active-rfcs/0013-composition-api.md).
The new Composition API is Vue’s approach to building Components in Vue 3. It’s a set of
additive, function-based APIs, that allow flexible composition of component logic.
With the new approach in hand, you group all the code required for one feature inside a single
composable function. This function can live inside the component itself, or in its own file. Thus,
your component gets composed out of smaller functions/features.
Therefore, a feature implemented in a Vue app is spread across multiple Options in the current
Vue 2 runtime. While, in Vue 3, the same feature is built inside a single composable function.
This way, readability and maintainability are greatly improved!
I won’t delve into more details on the new Composition API. However, I invite you to read my
article on this topic: Vue 3 Composition API, do you really need it?
(https://labs.thisdot.co/blog/vue-3-composition-api-do-you-really-need-it)
87
88
template>. Most of the
Currently, in Vue 2, you cannot have multiple roots inside a single <
div> to act as a single root.
time we overcome this limitation by introducing an extra <
template>.
Vue 3 introduces the Fragment API to allow having multiple root nodes in a single <
Vue 2 reads the object returned from the Component d ata() function, loops over the keys of
the object, and defines them as properties on the Vue instance.
This method has its own caveats. Two well-known issues are:
88
89
Vue 3 implements reactivity via Proxies
(http://exploringjs.com/es6/ch_proxies.html#sec_proxies-explained). Proxies were introduced in
ES6 or ES2015. By using them, the above two caveats no longer exist! Here’s an example of
ata() function:
defining a Proxy to wrap an array defined on the object returned by the d
89
90
In Closing
Thank you for choosing to purchase or download a copy of The Ultimate Guide to VueJS. While it is my
hope that readers will use this guide as a springboard to launch their further exploration into this amazing
framework, I also believe that this will be a helpful resource to keep on hand in order to reference core
concepts in VueJS in the future. If you have any questions about concepts discussed in this book, please
do not hesitate to reach out to me on Twitter (https://twitter.com/bhaidar).
I also want to express my sincere appreciation to everyone at This Dot Labs, and beyond, who supported
me in bringing this book to the web development community. If you would like to learn more about the
work that This Dot Labs does to support enterprise web development teams, as well as all of the free
educational resources they make available through This Dot Media, visit https://labs.thisdot.co/.
After graduating, he lectured, mentored, and served as a guest speaker at the very University from which
he graduated.
He then went on to become a published author (Professional ASP.NET 3.5 Security, Membership, and
Role Management with C# and VB) at just 26, before being picked up by Microsoft, and awarded 10
consecutive annual MVP awards in ASP.NET. Additionally, he earned a Microsoft Certified Trainer tag,
and a Project Management Professional PMP in 2012.
Today, as a Full Stack Engineer, he is highly regarded in his field. Fluent in ASP.NET Core, Node.js, PHP
Laravel, Angular, Vue.js, JavaScript, GraphQL, Databases, among other technologies, he has become a
highly sought after consultant.
With well over 100 CODE Magazine articles, online forums, and private clients, he has extensive
knowledge of all things code and continues to grow and thrive in all aspects of his career.
90
91
92
93
94
95