.Vue.js.2.Web.Development.Practical.guide.to.building.end To End.web.development.solutions.with.Vue.js.2

.Vue.js.2.Web.Development.Practical.guide.to.building.end-to-end.web.development.solutions.with.Vue.js.2

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 693

Download.Vue.js.2.Web.Development.Practical.guide.to.building.end-to-end.web.development.solutions.with.Vue.js.2
Open PDF In BrowserView PDF
Complete Vue.js 2 Web
Development

Practical guide to building end-to-end web development
solutions with Vue.js 2

Mike Street
Andrea Passaglia
Paul Halliday

BIRMINGHAM - MUMBAI

Complete Vue.js 2 Web Development
Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the
publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the authors nor Packt Publishing or its dealers
and distributors will be held liable for any damages caused or alleged to have been caused
directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
First Published: December 2018
Production Reference: 1211218

Published by Packt Publishing Ltd.
Livery Place, 35 Livery Street
Birmingham, B3 2PB, U.K.
ISBN 978-1-78995-990-1
www.packtpub.com

mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as
well as industry-leading tools to help you plan your personal development and advance
your career. For more information, please visit our website.

Why Subscribe?
Spend less time learning and more time coding with practical eBooks and Videos
from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content

Packt.com
Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at www.packt.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
customercare@packtpub.com for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a
range of free newsletters, and receive exclusive discounts and offers on Packt books and
eBooks.

Contributors
About the Authors
Mike Street (aka mikestreety) is a frontend developer from Brighton, UK. Specializing in
Gulp, SCSS, HTML, and Vue, he has been developing websites professionally since 2010.
After making his first Vue app as an experimental side project, he's been hooked ever since.
When not developing on the web, Mike likes to explore the Sussex countryside on his
bike, start a new side-project without finishing the last, or heading to the cinema.
Andrea Passaglia was born in Genoa, in northern Italy. Interested in technology since his
parents gave him a toy computer when he was a boy, he started studying web technologies
at an early age. After obtaining his master's degree in computer engineering he worked on
the design and implementation of web interfaces for companies of various sizes and in
different industries (healthcare, fashion, tourism, and transport).
In 2016 he moves in the silicon valley of Europe to tackle new problems in the banking
industry at the Edgeverve Dublin Research and Development Labs.
A backend technologist by trade, Vue.js is his first tool to bring to life his creations when it
comes to the frontend.
Andrea is married to a lovely Russian girl from Siberia and they often cook together mixing
culinary traditions.
Paul Halliday (BSc Hons) is a Developer Advocate with a focus on fastmoving technologies. His online courses have taught over 25,000 students across a wide
variety of software development subjects. He's also a Progress Developer Expert with
expertise in NativeScript and Kendo UI.

Packt Is Searching for Authors Like You
If you're interested in becoming an author for Packt, please visit authors.packtpub.com
and apply today. We have worked with thousands of developers and tech professionals,
just like you, to help them share their insight with the global tech community. You can
make a general application, apply for a specific hot topic that we are recruiting an author
for, or submit your own idea.

Table of Contents
Preface

1

Chapter 1: Getting Started with Vue.js
Creating the workspace
Application space
Vue library

Initializing Vue and displaying the first message
Computed values
Methods and reusable functions
Summary
Chapter 2: Displaying, Looping, Searching, and Filtering Data
HTML declarations
v-html
Declarative rendering

Conditional rendering
v-if
v-else

v-for and displaying our data
Creating links using v-html
Format balance
Format registered date

Filtering our data

Building the form
Binding the inputs

Showing and hiding Vue content
Filtering our content
Filtering our filters

Changing CSS classes
Filtering and custom classes
Summary
Chapter 3: Optimizing your App and Using Components to Display Data
Optimizing the code
Reducing the number of filter variables and grouping logically
Combining the format functions
Autodetection formatting
Passing in a second variable

Creating the method

7
8
8
9
9
12
15
18
19
20
20
21
22
22
23
25
27
28
28
29
29
31
32
34
39
40
44
48
49
49
51
54
54
55
56

Table of Contents

Reducing the number of hard-coded variables and properties, and reducing
redundancy

Creating Vue components

Creating and initializing your component
Using your component

Using component data and methods
Passing data to your component – props
Passing data to your component – slots
Creating a repeatable component

Creating component methods and computed functions
CSS class functions
Formatted value functions

Making the filtering work again with props

Making the filters a component

Creating the component
Resolving JavaScript errors
Using custom events to change the filter field
Updating the filter query

Summary
Chapter 4: Getting a List of Files Using the Dropbox API
Getting started—loading the libraries
Creating a Dropbox app and initializing the SDK
Displaying your data and using Vue to get it
Create the component
Retrieve the Dropbox data
The Vue life cycle hooks
Displaying the Dropbox data
More file meta information
Formatting the file sizes

Adding a loading screen
Animating between states
Summary
Chapter 5: Navigating through the File Tree and Loading Folders from
the URL
Separating out files and folders
Making file and folder components
Linking folders and updating the structure
Creating a breadcrumb from the current path
Adding the ability to download files
Updating the URL hash and using it to navigate through the folders
Showing the folder based on the URL
Displaying an error message
Using the back and forward buttons in your browser

[ ii ]

58
61
62
63
64
65
68
73
76
76
77
81
85
85
87
87
89
94
95
96
97
98
98
99
100
102
104
105
106
109
111
112
113
115
116
120
127
129
131
131
133

Table of Contents

Removing unneeded code
Updating the structure with a URL change and setting Vue data outside of the
instance

Final Code
Summary
Chapter 6: Caching the Current Folder Structure Using Vuex
Including and initializing Vuex
Utilizing the store
Retrieving the message
Updating the message

Using the Vuex store for the folder path

Updating the path methods to use store commits
Using the path variable

Updating the breadcrumb component
Updating the dropbox-viewer component to work with Vuex

Caching the folder contents
Loading data from the store if it exists
Loading the data from the store
Only storing new data

Summary
Chapter 7: Pre-Caching Other Folders and Files for Faster Navigation
Caching subfolders
Planning app methods
Creating the getFolderStructure method
Showing the data with the displayFolderStructure method

Set the loading state to true and create an empty structure object
Load the contents of the getFolderStructure method
Loop through the result and add each item to either the folders or files array
Update the global structure object and remove the loading state
Instigating the method

Caching the subfolders

Alternative caching method

Caching parent folders

Caching parent folders once

Caching download links on files
The complete code—with added documentation
Summary
Chapter 8: Introducing Vue-Router and Loading URL-Based
Components
Installing and initializing Vue-router
Changing the folder for Vue-router
Linking to the different routes
Linking to sub-routes
[ iii ]

133
135
139
143

144
146
147
148
149
149
150
151
151
152
155
159
159
160
165
166
167
168
169
173
174
174
175
176
176
178
179
181
184
187
189
198
199
200
204
204
206

Table of Contents

Dynamic routes with parameters
GET parameters
Using props

Setting prop defaults
Using static props

Nested routes
Creating a 404 page
Naming components, routes, and views
Naming components
Naming routes
Named views

Programmatically navigating with, redirecting, and adding an alias
Navigating programmatically
Redirecting
Alias routes

Summary
Chapter 9: Using Vue-Router Dynamic Routes to Load Data
Outline and plan your app
Components

Route components
HTML components

Paths

Create initial files
Server setup

Storing the file locally
Using a remote server
Setting up local server

Loading CSV

Loading a CSV with d3
Loading a CSV with CSV Parser
Unifying Shopify CSV data
Storing the products

Displaying a single product
Page Not Found
Selecting the right product
Catching products not found

Displaying product information
Product images

Product variations

Variations display table

Using a key with loops
Displaying the variations in a table

Displaying variations in a select box

Updating the product details when switching URLs
[ iv ]

207
212
212
214
216
217
220
221
221
222
224
226
227
227
228
229
230
230
231
231
232
232
233
236
236
237
237
238
239
241
241
243
245
246
247
250
253
255
261
261
261
262
269
276

Table of Contents

Summary
Chapter 10: Building an E-Commerce Store - Browsing Products
Listing the products
Adding a new route
Looping through products

Creating pagination

Calculating the values
Displaying a paginated list
Creating paginating buttons
Updating the URL on navigation
Creating pagination links
Updating the items per page

Creating the ListProducts component
Creating a curated list for the home page
Showing more information
Creating categories
Creating a category list
Creating a "miscellaneous" category

Displaying the categories
Displaying products in a category
Code optimization

Ordering products in a category
Store the product price
Wiring up the ordering

Creating Vuex getters
Building the filtering component based on products
Dynamically creating filters
Resetting filters

Updating the URL on checkbox filter change
Preselecting filters on page load

Filtering the products
Summary
Chapter 11: Building an E-Commerce Store - Adding a Checkout
Creating the basket array placeholder
Adding product information to the store
Creating the store mutation to add products to the basket

Updating the Add to basket button when adding an item
Showing the product count in the header of the app
Calculating the basket quantity

Finalizing the Shop Vue-router URLs
Building the Order process and ListProducts component
Order Confirmation screen
Using Vue filters to format the price

[v]

280
281
281
282
283
283
283
287
288
290
291
294
295
299
301
304
304
309
311
314
317
319
320
322
324
329
337
339
340
341
342
346
347
347
349
349
352
354
355
356
358
359
361

Table of Contents

Calculating a total price

Creating an Order Checkout page

Copying details between addresses

Creating an editable basket

Creating editable fields
Removing items from your cart

Completing the shop SPA
Summary
Chapter 12: Using Vue Dev Tools and Testing Your SPA
Using the Vue.js developer tools
Inspecting Vue components data and computed values
Viewing Vuex mutations and time-travel
Previewing event data

Testing your SPA

Command-line unit testing
Browser automation

Summary
Chapter 13: Transitions and Animations
Introduction
Integrating with third-party CSS animation libraries such as
animate.css
Getting ready
How to do it...
How does it work...

Adding your own transition classes
Getting ready
How to do it...
How it works...

Animating with JavaScript instead of CSS
Getting ready
How to do it...
How it works...
There's more...

Transitioning on the initial render
Getting ready
How to do it...
How it works...

Transitioning between elements
Getting ready
How to do it...
How it works...
There's more...

Transitioning between more than two elements
Setting the key attribute dynamically

[ vi ]

362
364
366
369
370
372
373
374
375
376
376
377
379
380
380
381
382
383
383
384
384
385
387
388
388
388
389
390
391
391
392
394
396
396
396
398
399
399
399
401
402
402
403

Table of Contents

Letting an element leave before the enter phase in a transition
Getting ready
How to do it...

The two elements problem
Transition modes

How it works...

Adding entering and leaving transitions for elements of a list
Getting ready
How to do it...
How it works...

Transitioning elements that move in a list
Getting ready
How to do it...
How it works...

Animating the state of your components
Getting ready
How to do it...
How it works...

Packaging reusable transitions into components
Getting ready
How to do it...

Building the basic web page
Building the reusable transition
Using our transition with the elements in our page

How it works...

Dynamic transitions
Getting ready
How to do it...
How it works...

Chapter 14: Vue Communicates with the Internet
Introduction
Sending basic AJAX requests with Axios
Getting ready
How to do it...
How it works...

Validating user data before sending it
Getting ready
How to do it...
How it works...

Creating a form and sending data to your server
Getting ready
How to do it...
How it works...
There's more...

Recovering from an error during a request
[ vii ]

404
404
404
404
406
406
407
407
407
409
409
410
410
412
413
414
414
416
417
418
418
418
420
420
421
422
422
422
425
426
426
427
427
427
428
431
431
431
432
433
433
433
436
437
437

Table of Contents

Getting ready
How to do it...
How it works...

Creating a REST client (and server!)
Getting ready
How to do it...
How it works...

Implementing infinite scrolling
Getting ready
How to do it...
How it works...

Processing a request before sending it out
Getting ready
How to do it...
How it works...

Preventing XSS attacks to your app
Getting ready
How to do it...
How it works...

Chapter 15: Single Page Applications
Introduction
Creating an SPA with vue-router
Getting ready
How to do it…
How it works…
There's more…

Fetching data before switching route
Getting ready
How to do it…
How it works…

Using named dynamic routes
Getting ready
How to do it…
How it works…

Having more than one router-view in your page
Getting ready
How to do it…
How it works…

Compose your routes hierarchically
Getting ready
How to do it...
How it works…

Using route aliases
Getting ready

[ viii ]

438
438
442
442
443
443
446
447
447
447
449
450
450
450
452
453
453
453
454
456
456
457
457
457
460
460
461
461
461
463
464
464
465
467
468
468
468
470
471
471
471
474
475
475

Table of Contents

How to do it…
How it works…

Adding transitions between your routes
Getting ready
How to do it…
How it works…

Managing errors for your routes
Getting ready
How to do it…
How it works…

Adding a progress bar to load pages
Getting ready
How to do it…
How it works…

How to redirect to another route
Getting ready
How to do it…
How it works…
There's more…

Redirecting to 404s
Named redirecting
Redirecting with parameters
Dynamic redirecting

Saving scrolling position when hitting back
Getting ready
How to do it…
How it works…

Chapter 16: Organize + Automate + Deploy = Webpack
Introduction
Extracting logic from your components to keep the code tidy
Getting ready
How to do it...

Creating a clean Webpack project
Building the compound interest calculator

How it works...

Bundling your component with Webpack
Getting ready
How to do it...
How it works...
There's more...

Organizing your dependencies with Webpack
Getting ready
How to do it...
How it works...

Using external components in your Webpack project
[ ix ]

476
478
478
478
478
480
480
480
481
483
483
483
483
485
486
486
486
488
488
488
488
489
489
489
490
490
494
495
495
495
496
496
496
497
500
500
500
501
508
508
509
509
509
513
513

Table of Contents

Getting ready
How to do it...
How it works...

Developing with continuous feedback with hot reloading
Getting ready
How to do it...
How it works...

Using Babel to compile from ES6
Getting ready
How to do it...
How it works...

Running a code linter while developing
Getting ready
How to do it...
How it works...

Using only one command to build both a minified and a
development .js file
Getting ready
How to do it…
How it works...

Releasing your components to the public
Getting ready
How to do it...
How it works...

Chapter 17: Advanced Vue.js - Directives, Plugins, and Render
Functions
Introduction
Creating a new directive
Getting ready
How to do it...
How it works…

Using WebSockets in Vue
Getting ready
How to do it...
How it works...

Writing a plugin for Vue
Getting ready
How to do it...
How it works...

Rendering a simple component manually
Getting ready
How to do it...
How it works...

Rendering a component with children
[x]

513
513
516
518
518
519
522
523
523
523
525
526
526
526
529
530
530
530
532
532
533
533
538
541
541
542
542
542
544
544
544
545
547
549
549
549
553
553
553
554
554
555

Table of Contents

Getting ready
How to do it...
How it works...

Using JSX to render a component
Getting ready
How to do it...
How it works...
There's more...

Creating a functional component
Getting ready
How to do it...
How it works...

Building a responsive table with higher-order components
Getting ready
How to do it...
How it works...

Chapter 18: Large Application Patterns with Vuex
Introduction
Dynamically loading pages in your vue-router
Getting ready
How to do it...
How it works...
There's more...

Building a simple storage for the application state
Getting ready
How to do it...
How it works...

Understanding Vuex mutations
Getting ready
How to do it...
How it works...
There's more...

Listing your actions in Vuex
Getting ready
How to do it...
How it works...

Separating concerns with modules
Getting ready
How to do it...
How it works...

Building getters to help retrieve your data
Getting ready
How to do it...
How it works...

[ xi ]

555
556
558
559
559
559
560
560
561
561
561
564
565
565
565
569
571
571
572
572
572
575
576
576
576
577
581
581
581
581
583
584
585
586
586
588
589
589
589
592
593
593
594
595

Table of Contents

Accessing other getters
Passing an argument

595
596
596
596
596
597
597
599
601

Testing your store
Getting ready
How to do it...

Software requirements
Testing mutations
Testing actions

How it works...

Chapter 19: Integrating with Other Frameworks
Introduction
Building universal applications with Electron
Getting ready
How to do it...
How it works...

Using Vue with Firebase
Getting ready
How to do it...
How it works...

Creating a real-time app with Feathers
Getting ready
How to do it...
How it works...

Creating a reactive app with Horizon
Getting ready
How to do it...
How it works...

Chapter 20: Vue Router Patterns
Single Page Applications
Using the router

602
602
602
603
603
606
606
606
607
609
610
610
610
613
613
614
615
620
621
621
622
623
624
625
626
626
627
627
627
627
628
628
629
630
631
631

Creating routes
Dynamic routes
Route props

Component Navigation Guards
beforeRouteUpdate
beforeRouteEnter
beforeRouteLeave

Global router hooks
beforeEach
beforeResolve
afterEach
Resolution stack

Programmatic navigation
router.replace
router.go

[ xii ]

Table of Contents

Lazy loading routes

An SPA project

Enabling the router
Defining routes
Creating the UserList route
Getting data from an API
Creating a detail page
Child routes

Summary
Chapter 21: State Management with Vuex
What is Vuex?
State Management Pattern (SMP)
Thinking about state

Using Vuex

Creating a new store
Defining action types
Actions
Mutations
Getters
Combining elements
Payloads

Vuex and Vue devtools
Modules and scalability
Summary
Other Books You May Enjoy

632
635
636
636
637
638
639
642
646
647
647
648
650
651
651
652
652
653
653
654
656
660
662
664
665

Index

668

[ xiii ]

Preface
This Learning Path is divided into three sections, with each section bringing you closer to
developing high-end modern web applications with Vue.js 2. It starts with building
example applications to get well versed with the Vue.js ecosystem. You will learn to use
Vue.js by creating three single page applications that explore Vuex and vue-router, the
standard Vue tools for caching data and routing URLs for your applications. Going further,
the Learning Path will address some of the challenges in designing web applications with
Vue.js.
The Learning Path will have easy-to-follow recipes to help you tackle the challenges and
craft dynamic front end. You will learn to integrate web utilities like Babel and Webpack to
enhance your development workflow. Finally, towards the end, the course will introduce
you to several design patterns to help you write clean, maintainable, and reusable codes
with Vue framework.
At the end of the Learning Path, you will be confident with expertise in leveraging all the
components and productivity features of Vue.js and will be on your way to design your
web applications and execute it by writing clean code.

Who This Book Is For
The Learning Path is intended for JavaScript developers at any level of expertise who wants
to learn Vue.js and develop productive web applications with the power of the latest Vue.js.

What This Book Covers
Chapter 1, Getting Started with Vue.js, shows how to get started with Vue by including the

JavaScript file. We then move onto initializing your first Vue instance and looking at the
data object along with examining computed functions and properties and finally learning
about Vue methods.
Chapter 2, Displaying, Looping, Searching, and Filtering Data, describes how to display lists

and more complex data with Vue using v-if , v-else and v-for. It then looks at how to
filter the lists using form elements, followed by applying conditional CSS classes based on
the data.

Preface
Chapter 3, Optimizing Our App and Using Components to Display Data, is about optimizing

our Vue.js code by reducing the repetition and logically organizing our code. Once
complete, it looks at how to create Vue components and use them with Vue, how to use
props and slots with components, and utilizing events to transfer data between
components.

Chapter 4, Getting a List of Files Using the Dropbox API, presents loading and querying the

Dropbox API and listing the directories and files from your Dropbox account. It then looks
at adding a load state to your app along with using Vue animations.
Chapter 5, Navigating through the File Tree and Loading Folders from the URL, explains how to

create a component for both files and folders, and add links to the folder component to
update the directory listing. it also covers how to add a download button to the file
component and create a breadcrumb component so the user can easily navigate back up the
tree and dynamically update the browser URL, so if a folder is bookmarked or a link is
shared, the correct folder loads.
Chapter 6, Caching the Current Folder Structure Using Vuex, shows how to get started

with Vuex along with storing and retrieving data from the Vuex Store. It then looks at how
to integrate Vuex with our Dropbox app, how to cache the current Dropbox folder's
contents, and loading data from the store if required.
Chapter 7, Pre-Caching Other Folders and Files for Faster Navigation, describes the

process of pre-caching folders, storing the parent folder's contents, and how to cache the
download links for the files.
Chapter 8, Introducing Vue-Router and Loading URL-Based Components, explores Vue-Router

initialization and its options and how to create links with Vue-Router. It then looks at how
to make dynamic routes to update the View based on the URL. From there, it describes how
to use props with URLs, nest and name routes, and navigate programmatically.
Chapter 9, Using Vue-Router Dynamic Routes to Load Data, is about outlining our

components and routes, loading a product CSV file and creating an individual product
page with images and product variations.
Chapter 10, Building an E-Commerce Store, Browsing Products, describes how to create a

homepage listing page with specific products, create a category page with a reusable
component, create an ordering mechanism, create filters dynamically, and allow the user to
filter the products.

[2]

Preface
Chapter 11, Building an E-Commerce Store, Adding a Checkout, is about building the

functionality to allow the user to add and remove products to their basket, allow a user to
check out and add an order confirmation page.
Chapter 12, Using Vue Dev Tools and Testing Your SPA, covers the usage of the Vue

developer tools with the applications we've developed and has an overview of testing tools
and applications.
Chapter 13, Transitions and Animations, where you learn how transitions and animations

work to bring more life to your apps. You will also integrate with external CSS libraries.

Chapter 14, Vue Communicates with the Internet, is where you make your first AJAX call and

create forms and a full-fledged REST client (and server!).

Chapter 15, Single Page Applications, is where you use vue-router to create static and

dynamic routes to create a modern SPA.

Chapter 16, Organize + Automate + Deploy = Webpack, is where you actually publish your

accurately crafted components to npm and learn how Webpack and Vue play together in
the process.
Chapter 17, Advanced Vue.js, is where you explore directives, plugins, functional

components, and JSX.

Chapter 18, Large Application Patterns with Vuex, is where you structure your application

with tested patterns using Vuex to make sure your apps are maintainable and performant.
Chapter 19, Integrating with Other Frameworks, is where you build four different

applications with Vue and Electron, Firebase, Feathers, and Horizon.

Chapter 20, Vue Router Patterns, describes how routing is a vitally important part of any

SPA. This chapter focuses on the Vue route and looks at routing a user between multiple
pages. It goes through everything from matching paths and components to dynamic
matching with navigation parameters, regular expressions, and more.
Chapter 21, State Management with Vuex, demonstrates state management with Vuex. It

starts by looking at the Flux architecture and unidirectional data flow. Then, it takes a look
at Vuex, a state management system for Vue. The chapter also looks at implementing this in
an application, as well as common pitfalls and usage patterns. It goes on to the Vuedevtools to capture actions and Vue instance data.

[3]

Preface

To Get the Most out of This Book
For this book, the reader will need the following:
A text editor or IDE to write code. It can be as simple as Notepad or TextEdit, but
one with syntax highlighting such as Sublime Text, Atom, or Visual Studio
Code is recommended.
A web browser.
A Dropbox user account with files and folders.

Download the Example Code Files
You can download the example code files for this book from your account at
www.packt.com. If you purchased this book elsewhere, you can visit
www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
1.
2.
3.
4.

Log in or register at www.packt.com.
Select the SUPPORT tab.
Click on Code Downloads & Errata.
Enter the name of the book in the Search box and follow the onscreen
instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https:/​/​github.​com/
PacktPublishing/​Complete-​Vue.​js-​2-​Web-​Development. In case there's an update to the
code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available
at https:/​/​github.​com/​PacktPublishing/​. Check them out!

[4]

Preface

Conventions Used
In this book, you will find a number of text styles that distinguish between different kinds
of information. Here are some examples of these styles and an explanation of their
meaning.
Code words in the text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Just
assign the names of the layers you want to activate to
the VK_INSTANCE_LAYERS environment variable."
A block of code is set as follows:
{{ calculateSalesTax(shirtPrice) }}
Any command-line input or output is written as follows: $ npm install $ npm run dev Bold: New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Select System info from the Administration panel." Warnings or important notes appear like this. Tips and tricks appear like this. Get in Touch Feedback from our readers is always welcome. General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at customercare@packtpub.com. [5] Preface Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details. Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material. If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com. Reviews Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you! For more information about Packt, please visit packt.com. [6] 1 Getting Started with Vue.js Vue (pronounced view) is a very powerful JavaScript library created for building interactive user interfaces. Despite having the ability to handle large single-page applications, Vue is also great for providing a framework for small, individual use cases. Its small file size means it can be integrated into existing ecosystems without adding too much bloat. It was built to have a simple API, which makes it easier to get started in comparison with its rivals: React and Angular. Although it borrows some of the logic and methodologies from these libraries, it has identified a need for developers for a simpler library for building applications. Unlike React or Angular, one of the benefits of Vue is the clean HTML output it produces. Other JavaScript libraries tend to leave the HTML scattered with extra attributes and classes in the code, whereas Vue removes these to produce clean, semantic output. In this chapter, we will look at: How to get started with Vue by including the JavaScript file How to initialize your first Vue instance and look at the data object Examining computed functions and properties Learning about Vue methods Getting Started with Vue.js Chapter 1 Creating the workspace To use Vue, we first need to include the library in our HTML and initialize it. For the examples in the first section of this book, we are going to be building our application in a single HTML page. This means the JavaScript to initialize and control Vue will be placed at the bottom of our page. This will keep all our code contained, and means it will easily run on your computer. Open your favorite text editor and create a new HTML page. Use the following template as a starting point: Vue.js App
The main HTML tags and structure should be familiar to you. Let's run over a few of the other aspects. Application space This is the container for your application and provides a canvas for Vue to work in. All the Vue code will be placed within this tag. The actual tag can be any HTML element main, section, and so on. The ID of the element needs to be unique, but again, can be anything you wish. This allows you to have multiple Vue instances on one page or identify which Vue instance relates to which Vue code:
During the tutorials, this element with the ID will be referred to as the app space or view. It should be noted that all HTML and tags and code for your application should be placed within this container. [8] Getting Started with Vue.js Chapter 1 Although you can use most HTML tags for your application space, you cannot initialize Vue on the or tags - if you do so, Vue will throw a JavaScript error and will fail to initialize. You will have to use an element inside your body. Vue library For the examples in this book, we are going to be using a hosted version of Vue.js from a CDN (Content Delivery Network) unpkg. This ensures that we have the latest version of Vue in our application, and also means we do not need to create and host other JavaScript files. Unpkg is an independent site that hosts popular libraries. It enables you to quickly and easily add a JavaScript package to your HTML, without having to download and host the file yourself: When deploying your code, it is a good practice to serve up your libraries from local files rather than relying on CDNs. This ensures that your implementation will work with the currently - saved version, should they release an update. It will also increase the speed of your application, as it will not need to request the file from another server. The script block following the library include is where we are going to be writing all our JavaScript for our Vue application. Initializing Vue and displaying the first message Now that we have a template set up, we can initialize Vue and bind it to the HTML app space by using the following code: const app = new Vue().$mount('#app'); This code creates a new instance of Vue and mounts it on the HTML element with the ID of app. If you save your file and open it up in a browser, you will notice nothing has happened. However, under the hood, this one line of code has linked the div with the app variable, which is an instance of a Vue application. [9] Getting Started with Vue.js Chapter 1 Vue itself has many objects and properties that we can now use to build our app. The first one you will encounter is the el property. Using an HTML ID, this property tells Vue which element it should bind to and where the app is going to be contained. This is the most common way of mounting your Vue instance and all Vue code should happen within this element: const app = new Vue({ el: '#app' }); When the el property isn't specified in the instance, Vue initializes in an unmounted state—this allows any functions or methods you may have specified to run before mounting, to run and complete. You can then independently call the mounting function when ready. Behind the scenes, when using the el property, Vue is mounting the instance using a $.mount function. If you do want to wait, the $mount function can be called separately, for example: const app = new Vue(); // When ready to mount app: app.$mount('#app'); However, as we will not need to delay the execution of our mount timing throughout the book, we can use the el element with the Vue instance. Using the el property is also the most common way of mounting the Vue app. Alongside the el value, Vue has a data object that contains any data we need to access the app or app space. Create a new data object within the Vue instance and assign a value to a property by doing the following: const app = new Vue({ el: '#app', data: { message: 'Hello!' } }); Within the app space, we now have access to the message variable. To display data within the app, Vue uses the Mustache templating language to output data or variables. This is achieved by placing the variable name between double curly brackets {{ variable }}. Logic statements, such as if or foreach, get HTML attributes, which will be covered later in the chapter. [ 10 ] Getting Started with Vue.js Chapter 1 Within the app space, add the code to output the string:
{{ message }}
Save the file, open it up in your browser, and you should be presented with your Hello! string. If you don't see any output, check the JavaScript console to see if there are any errors. Ensure the remote JavaScript file is loading correctly, as some browsers and operating systems require additional security steps before allowing some remote files to be loaded when viewing pages locally on your computer. The data object can handle multiple keys and data types. Add some more values to the data object and see what happens - make sure you add a comma after each value. Data values are simple JavaScript and can handle basic math, too - try adding a new price key and setting the value to 18 + 6 to see what happens. Alternatively, try adding a JavaScript array and printing it out: const app = new Vue({ el: '#app', data: { message: 'Hello!', price: 18 + 6, details: ['one', 'two', 'three'] } }); In your app space, you can now output each of those values - {{ price }} and {{ details }} now output data - although the list may not be quite what you had expected. We'll cover using and displaying lists in Chapter 2, Displaying, Looping, Searching, and Filtering Data. All the data in Vue is reactive and can be updated by either the user or the application. This can be tested by opening up the browser's JavaScript console and updating the content yourself. Try typing app.message = 'Goodbye!'; and pressing Enter - your app's content will update. This is because you are referencing the property directly - the first app refers to the const app variable that your app is initialized to in your JavaScript. The period denotes a property within there, and the message refers to the data key. You could also update app.details or price to anything you want! [ 11 ] Getting Started with Vue.js Chapter 1 Computed values The data object in Vue is great for storing and retrieving data directly, however, there may be times where you want to manipulate the data before outputting it in your applications. We can do that using the computed object in Vue. Using this technique, we are able to start adhering to the MVVM (Model-View-ViewModel) methodology. MVVM is a software architectural pattern where you separate out various parts of your application into distinct sections. The Model (or data) is your raw data input - be it from an API, database, or hardcoded data values. In the context of Vue, this is typically the data object we used earlier. The view is the frontend of your application. This should just be used for outputting the data from the Model, and should not contain any logic or data manipulation, with the exception of some unavoidable if statements. For the Vue applications, this is all the code placed within the
tags. The ViewModel is the bridge between the two. It allows you to manipulate the data from the Model before it is output by the view. Examples of this could range from changing a string to uppercase or prefixing a currency symbol, up to filtering out discounted products from a list or calculating the total value of a field across an array. In Vue, this is where the computed object comes in. The computed object can have as many properties as required - however, they must be functions. These functions can utilize data already on the Vue instance and return a value, be it a string, number, or array that can then be used in the view. The first step is to create a computed object within our Vue application. In this example, we are going to use a computed value to convert our string to lowercase, so set the value of message back to a string: const app = new Vue({ el: '#app', data: { message: 'Hello Vue!' }, computed: { } }); [ 12 ] Getting Started with Vue.js Chapter 1 Don't forget to add a comma (,) after the closing curly bracket (}) of your data object so Vue knows to expect a new object. The next step is to create a function inside the computed object. One of the hardest parts of development is naming things - make sure the name of your function is descriptive. As our application is quite small and our manipulation basic, we'll name it messageToLower: const app = new Vue({ el: '#app', data: { message: 'HelLO Vue!' }, computed: { messageToLower() { return 'hello vue!'; } } }); In the preceding example, I've set it to return a hardcoded string, which is a lowercased version of the contents of the message variable. Computed functions can be used exactly as you would use a data key in the view. Update the view to output {{ messageToLower }} instead of {{ message }} and view the result in your browser. There are a few issues with this code, however. Firstly, if the value of messageToLower was being hardcoded, we could have just added it to another data property. Secondly, if the value of message changes, the lowercase version will now be incorrect. Within the Vue instance, we are able to access both data values and computed values using the this variable - we'll update the function to use the existing message value: computed: { messageToLower() { return this.message.toLowerCase(); } } The messageToLower function now references the existing message variable and, using a native JavaScript function, converts the string to lower case. Try updating the message variable in your application, or in the JavaScript console, to see it update. [ 13 ] Getting Started with Vue.js Chapter 1 Computed functions are not just limited to basic functionality - remember, they are designed to remove all logic and manipulations from the view. A more complex example might be the following: const app = new Vue({ el: '#app', data: { price: 25, currency: '$', salesTax: 16 }, computed: { cost() { // Work out the price of the item including salesTax let itemCost = parseFloat( Math.round((this.salesTax / 100) * this.price) + this.price).toFixed(2); // Add text before displaying the currency and amount let output = 'This item costs ' + this.currency + itemCost; // Append to the output variable the price without salesTax output += ' (' + this.currency + this.price + ' excluding salesTax)'; // Return the output value return output; } } }); Although this might seem advanced at first glance, the code is taking a fixed price and calculating what it would be with sales tax added. The price, salesTax, and currency symbol are all stored as values on the data object and accessed within the cost() computed function. The view outputs {{ cost }}, which produces the following: This item costs $29.00 ($25 excluding sales tax) Computed functions will recalculate and update if any data is updated, by either the user or the application itself. This allows for our function to dynamically update based on the price and salesTax values. Try one of the following commands in the console in your browser: app.salesTax = 20 app.price = 99.99 [ 14 ] Getting Started with Vue.js Chapter 1 The paragraph and prices will update instantly. This is because computed functions are reactive to the data object and the rest of the application. Methods and reusable functions Within your Vue application, you may wish to calculate or manipulate data in a consistent or repetitive way or run tasks that require no output to your view. For example, if you wanted to calculate the sales tax on every price or retrieve some data from an API before assigning it to some variables. Rather than creating computed functions for each time, we need to do this, Vue allows you to create functions or methods. These get declared in your application and can be accessed from anywhere - similar to the data or computed functions. Add a method object to your Vue application and note the updates to the data object: const app = new Vue({ el: '#app', data: { shirtPrice: 25, hatPrice: 10, currency: '$', salesTax: 16 }, methods: { } }); Within the data object, the price key has been replaced with two prices - shirtPrice and hatPrice. We'll create a method to calculate the sales tax for each of these prices. Similar to creating a function for the computed object, create a method function title called calculateSalesTax. This function needs to accept a single parameter, which will be the price. Inside, we will use the code from the previous example to calculate the sales tax. Remember to replace this.price with just the parameter name: price, as shown here: methods: { calculateSalesTax(price) { // Work out the price of the item including sales tax return parseFloat( Math.round((this.salesTax / 100) * price) + price).toFixed(2); [ 15 ] Getting Started with Vue.js Chapter 1 } } Pressing save will not do anything to our application - we need to call the function. In your view, update the output to use the function and pass in the shirtPrice variable:
{{ calculateSalesTax(shirtPrice) }}
Save your documents and check the result in the browser - is it what you expected? The next task is to prepend the currency. We can do that by adding a second method that returns the parameter passed into the function with the currency at the beginning of the number: methods: { calculateSalesTax(price) { // Work out the price of the item including sales tax return parseFloat( Math.round((this.salesTax / 100) * price) + price).toFixed(2); }, addCurrency(price) { return this.currency + price; } } In our view, we then update our output to utilize both methods. Rather than assigning to a variable, we can pass the first function, calculateSalesTax, as the parameter for the second addCurrency function. This works because of the first method, calculateSalesTax, accepts the shirtPrice parameter and returns the new amount. Instead of saving this as a variable and passing the variable into the addCurrency method, we pass the result directly into this function, which is the calculated amount: {{ addCurrency(calculateSalesTax(shirtPrice)) }} However, it would start to get tiresome having to write these two functions every time we needed to output the price. From here, we have two options: We can create a third method, titled cost() - which accepts the price parameter and passes the input through the two functions Create a computed function, such as shirtCost, which uses this.shirtPrice instead of having a parameter passed in [ 16 ] Getting Started with Vue.js Chapter 1 We could, alternatively, create a method titled shirtCost that does the same as our computed function; however, it's better to practice to use computed in this case. This is because computed functions are cached, whereas method functions are not. If you imagine our methods being a lot more complicated than they currently are, calling function after function repeatedly (for example, if we wanted to display the price in several locations) could have a performance impact. With computed functions, as long as the data does not change, you can call it as many times as you want, with the result being cached by the application. If the data does change, it only needs to recalculate once, and re-cache that result. Make a computed function for both the shirtPrice and hatPrice, so that both variables can be used in the view. Don't forget that to call the functions internally you must use the this variable - for example, this.addCurrency(). Use the following HTML code as the template for your view:

The shirt costs {{ shirtCost }}

The hat costs {{ hatCost }}

Have a go at creating the computed functions yourself before comparing against the following code. Don't forget that there are many ways to do things in development, so don't worry if your code works but doesn't match the following example: const app = new Vue({ el: '#app', data: { shirtPrice: 25, hatPrice: 10, currency: '$', salesTax: 16 }, computed: { shirtCost() { returnthis.addCurrency(this.calculateSalesTax( this.shirtPrice)) }, hatCost() { return this.addCurrency(this.calculateSalesTax( this.hatPrice)) }, }, methods: { calculateSalesTax(price) { [ 17 ] Getting Started with Vue.js Chapter 1 // Work out the price of the item including sales tax return parseFloat( Math.round((this.salesTax / 100) * price) + price).toFixed(2); }, addCurrency(price) { return this.currency + price; } } }); The result, although basic, should look like the following: Summary In this chapter, we learned how to get started with the Vue JavaScript framework. We examined the data, computed, and methods objects within the Vue instance. We covered how to use each one within the framework and utilize each of its advantages. [ 18 ] 2 Displaying, Looping, Searching, and Filtering Data In Chapter 1, Getting Started with Vue.js, we covered the data, computed, and method objects within Vue and how to display static data values. In this chapter, were are going to cover: Displaying lists and more complex data with Vue using v-if, v-else, and vfor Filtering the lists using form elements Applying conditional CSS classes based on the data The data we are going to be using is going to be randomly generated by the JSON generator service (http:/​/​www.​json-​generator.​com/​). This website allows us to get dummy data to practice with. The following template was used to generate the data we will be using. Copy the following into the left-hand side to generate data of the same format so the attributes match with the code examples, as follows: [ '{{repeat(5)}}', { index: '{{index()}}', guid: '{{guid()}}', isActive: '{{bool()}}', balance: '{{floating(1000, 4000, 2, "00.00")}}', name: '{{firstName()}} {{surname()}}', email: '{{email()}}', registered: '{{date(new Date(2014, 0, 1), new Date(), "YYYYMM-ddThh:mm:ss")}}' } ] Displaying, Looping, Searching, and Filtering Data Chapter 2 Before we get into building our simple app and displaying our users, we'll cover some more of the features of Vue and the HTML-specific attributes available in your view. These range from dynamically rendering content to looping through arrays. HTML declarations Vue allows you to use HTML tags and attributes to control and alter the view of your application. This involves setting attributes dynamically, such as alt and href. It also allows you to render tags and components based on data in the application. These attributes begin with a v- and, as mentioned at the beginning of this book, get removed from the HTML on render. Before we start outputting and filtering our data, we'll run through a few of the common declarations. v-html The v-html directive allows you to output content without using the mustache-style curly bracket syntax. It can also be used if your output contains HTML tags – it will render the output as HTML instead of plain text. The value of the HTML attribute is that of the data key or computed function name: View: In your view app space, add the v-html attribute to an element:
JavaScript: In the JavaScript, set the message variable to a string which contains some HTML elements: const app = new Vue({ el: '#app', data: { message: '

Hello!

' } }); [ 20 ] Displaying, Looping, Searching, and Filtering Data Chapter 2 You should try and avoid adding HTML to your Vue instance, as it starts to mix up the View in the ViewModel and Model of our MVVM structure. There is also the danger you output an invalid HTML tag inside another. You should only use v-html with data you trust, because using it with an external API could be a security concern as it would allow the API to have control over your application. A potentially malicious API could use vhtml to inject undesired content and HTML. Only use v-html with data you can fully trust. Declarative rendering Regular HTML attributes, such as the src of the tag, can be dynamically populated with Vue using the v-bind: attribute. This allows you to populate any existing attribute with data from your Vue application. This might be an image source or element ID. The bind option gets used by prepending the attribute you wish to populate. For example, if you wished to populate an image source with the value of a data key called imageSource, you would do the following: View: Create an img tag in your view app space, with a dynamic src attribute, using v-bind and a variable called imageSource.
JavaScript: Create a variable in your Vue JavaScript code called imageSource. Add the URL to the desired image: const app = new Vue({ el: '#app', data: { imageSource: 'http://via.placeholder.com/350x150' } }); The v-bind: attribute can be shortened to just :, so, for example, v-bind:src would become :src. [ 21 ] Displaying, Looping, Searching, and Filtering Data Chapter 2 Conditional rendering Using custom HTML declarations, Vue allows you to render elements and contents conditionally based on data attributes or JavaScript declarations. These include v-if, for showing a container whether a declaration equates to true, and v-else, to show an alternative. v-if The most basic example of this would be the v-if directive – determining a value or function if the block should be displayed. Create a Vue instance with a single div inside the view and a data key, isVisible, set to false. View: Start off with the view code as the following:
Now you see me
JavaScript: In the JavaScript, initialize Vue and create an isVisible data property: const app = new Vue({ el: '#app', data: { isVisible: false } }); Right now, your Vue app would be displaying the contents of your element. Now add the v-if directive to your HTML element with the value of isVisible:
Now you see me
[ 22 ] Displaying, Looping, Searching, and Filtering Data Chapter 2 Upon pressing save, your text should disappear. That is because the tag is being conditionally rendered based on the value, which is currently false. If you open up your JavaScript console and run the following code, your element should reappear: app.isVisible = true v-if doesn't just work with Boolean true/false values. You can check whether a data property is equal to a specific string:
Now you see me
For example, the preceding code checks whether a selected data property is equal to the value of yes. The v-if attribute accepts JavaScript operators, so can check not equals, bigger, or less than. The danger here is that your logic starts to creep into your View away from your ViewModel. To combat this, the attribute also takes functions as a value. The method can be as complicated as required but ultimately must return a true if you wish to show the code and a false if not. Bear in mind that if the function returns anything other than a false value (such as 0 or false) then the result will be interpreted as true. This would look something like this:
Now you see me
And your method could be as this: isSelected() { return selected == 'yes'; } If you don't wish to completely remove the element and only hide it, there is a more appropriate directive, v-show. This applies a CSS display property rather than manipulating the DOM – v-show is covered later in the chapter. v-else v-else allows you to render an alternative element based on the opposite of the v-if statement. If that results in true, the first element will be displayed; otherwise, the element containing v-else will. [ 23 ] Displaying, Looping, Searching, and Filtering Data Chapter 2 The element with v-else needs to directly follow the one containing vif; otherwise, your application will throw an error. v-else has no value and is placed within the element tag.
Now you see me
Now you don't
Adding the preceding HTML to your app space will only show one of the
elements – toggling the value in your console as we did earlier will reveal the other container. You can also use v-else-if should you wish to chain your conditions. An example of v-else-if is as follows:
Now you see me
You might see me
Now you don't
You might see me will be displayed if the isVisible variable equates to false, but the otherVisible variable equates to true. v-else should be used sparingly as can be ambiguous and might lead to false positive situation. [ 24 ] Displaying, Looping, Searching, and Filtering Data Chapter 2 v-for and displaying our data The next HTML declaration means we can start displaying our data and putting some of these attributes into practice. As our data is an array, we will need to loop through it to display each element. To do this, we will use the v-for directive. Generate your JSON and assign it to a variable called people. During these examples, the generated JSON loop will be displayed in the code blocks as [...]. Your Vue app should look like the following: const app = new Vue({ el: '#app', data: { people: [...] } }); We now need to start displaying each person's name in our View as a bulleted list. This is where the v-for directive comes in:
  • {{ person }}
The v-for loops through the JSON list and for every entry temporarily assigns it the person variable. We can then output the value or attributes of the variable. The v-for loop needs to be applied to the HTML element you want to be repeated, in this case,
  • . If you don't have a wrapping element or don't wish to use the HTML you can use the Vue