45,59 €
Learn the fundamentals of vue.js by creating complex SPAs with Vuex, vue-router and more
This book is for developers who know the basics of JavaScript and are looking to learn Vue.js with real examples. You should understand the basics of JavaScript functions and variables and be comfortable with using CSS or a CSS framework for styling your projects.
Vue.js is a frontend web framework which makes it easy to do just about anything, from displaying data up to creating full-blown web apps, and has become a leading tool for web developers. This book puts Vue.js into a real-world context, guiding you through example projects that helps you build Vue.js applications from scratch.
With this book, you will learn how to use Vue.js by creating three Single Page web applications. Throughout this book, we will cover the usage of Vue, for building web interfaces, Vuex, an official Vue plugin which makes caching and storing data easier, and Vue-router, a plugin for creating routes and URLs for your application.
Starting with a JSON dataset, the first part of the book covers Vue objects and how to utilize each one. This will be covered by exploring different ways of displaying data from a JSON dataset. We will then move on to manipulating the data with filters and search and creating dynamic values.
Next, you will see how easy it is to integrate remote data into an application by learning how to use the Dropbox API to display your Dropbox contents in an application
In the final section, you will see how to build a product catalog and dynamic shopping cart using the Vue-router, giving you the building blocks of an e-commerce store.
This book takes you three projects, with step-by-step instructions to help you understand the concepts of Vue and put it into practice.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 405
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 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 author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be 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 2017
Production reference: 1191217
ISBN 978-1-78829-346-4
www.packtpub.com
Author
Mike Street
Copy Editor
Safis Editing
Reviewers
Bogdan Balc
Silva, Pablo Henrique P.
Project Coordinator
Hardik Bhinde
Commissioning Editor
Kunal Chaudhari
Proofreader
Safis Editing
Acquisition Editor
Siddharth Mandal
Indexer
Tejal Daruwale Soni
ContentDevelopmentEditor
Aditi Gour
Graphics
Jason Monteiro
Technical Editor
Sushmeeta Jena
Production Coordinator
Aparna Bhagat
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.
Bogdan Balc is a Team Lead with a passion for frontend technologies. He has worked with JavaScript for the past 10 years from the emergence of jQuery and Ajax to modern full-fledged MVC frameworks. When he is not fiddling with some new JavaScript challenge, he spends his time playing sports and games with friends, as well as watching sports and movies.
Nowadays, he channels most of his efforts into making we3interactive one of the most successful and creative startups in Cluj.
His passion with Vue.js pushed him to collaborate on two other awesome Vue.js books in the past: Learning Vue.js by Olga Filipova and Vue.js 2 Cookbook by Andrea Passaglia.
Silva, Pablo Henrique P. is a frontend developer, speaker, writer, and community leader focused on helping companies and individuals succeed with their frontend applications.
As a frontend developer, he has been using Vue.js since version 1.0 and kept continues to use it in several current projects. His current job as a Squad Leader at a Brazilian company gave him the opportunity to lead several developer teams and to see the benefits of Vue.js while creating products and services.
As a writer, he is curious, likes to solve problems and his style of writing follows the tl;dr; (too long; didn't read) style, meaning he tries to be as clear and goal-minded as possible. He uses this style because he believes developers (such as himself) should learn things quickly and not waste time reading some long articles that have only one or two paragraphs of true meaningful information.
Pablo Henrique frequently speaks about, and writes about frontend in general, but has given many presentations about Vue.js.
I would like to start by thanking my wife, Chilly, for everything she's had to put up with while I've been writing this book. From the tears after I forgot to press save, to the elation after I typed the last full stop. She has encouraged me to write on those days where I've wanted to walk away and had to tolerate those nights where I couldn't stop writing. Thank you.
I would also like to thank my family, friends, and the "Wilmy gang" for the support they showed during the whole book-writing process. Most of them didn't understand a single thing I was talking about when asking me about my progress. Despite this, they managed to feign enough enthusiasm to keep me motivated – even my Gran expressed interest.
I would like to thank the publishers for giving me the opportunity to write this book. Thank you for giving me this experience.
Lastly, I would like to thank my colleagues at Liquid Light for encouraging me to be the best frontend developer, productivity hipster, and writer I can be. Without any of these people, this book wouldn't be here.
For support files and downloads related to your book, please visit www.PacktPub.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.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.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.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at www.amazon.in/dp/1788293460.
If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
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
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
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
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
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
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
Removing unneeded code
Updating the structure with a URL change and setting Vue data outside of the instance
Final Code
Summary
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
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
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
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
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
Summary
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 an "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
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
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
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
This book will cover the use of Vue.js 2. Vue can be used as both a frontend framework by including a JS file and also a backend framework with Node.js. The book was written using the frontend version of the framework—although it will be pointed out that it could easily be ported to using the node version if required, as the fundamentals of the framework remain the same in the two versions.
Vue is a framework that can be used for simple data display and creating full-blown web apps. This book will try and cover both ends of the spectrum while introducing plugins and add-ons to help with the creation of the bigger apps.
The use of Vue components will also be covered, including the benefits of using them over keeping all your data and methods contained within the main Vue instance. The book will also cover using the two most popular plugins for Vue: Vuex and Vue-Router. This book will not cover the process of styling the applications.
Vuex is a centralized state management pattern and library for Vue. It makes storing, manipulating, and accessing data a lot more manageable and is great for use with an app that requires a lot of data to be displayed. Vue-Router is used to handle navigation through the app, allowing different components to load depending on the URL.
Starting with a JSON dataset, the first part of the book will cover Vue objects and how to utilize each one. This will be covered by exploring different ways of displaying data from a JSON dataset. We will then move on to manipulating the data with filters and search and creating dynamic values.
Once complete, we will look at loading your data dynamically through an API—the example being the Dropbox API. Once the data is loaded, the book will walk through navigating through the folders while updating the URL and creating a download link for the files. We will then load in Vuex, and look at storing the data of each folder moving onto pre-caching the folders, making navigating through the app a lot quicker.
Lastly, we will look at creating an e-commerce frontend using the skills learned during previous projects while introducing new ones. Firstly, the products will be displayed in a list; using filters and search, you will be able to click on a product to find out more information and to add it to your basket. When ready, the "customer" will be able to view their basket and update items and quantities and finally check out.
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.
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 fof 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.
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.
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.
This book is for developers who are familiar with JavaScript but would like to explore the use of JavaScript MVVM frameworks for use with Single Page Applications (SPAs). They should be competent with HTML and familiar with CSS, so that they can to build and style the interfaces for the SPAs. This book takes the reader from initializing Vue and its basic functionality all the way to using advanced Vue plugins and techniques. The reader should be comfortable with JavaScript functions and variables and the use of ES6/ES2015 arrow functions.
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail [email protected], and mention the book's title on the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
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/Vue.JS-2.5-by-Example. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/VueJS2.5+byExample_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
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 the first part of this book, we are going to build an application that uses a JSON string to display data. We will then look at filtering and manipulating data, before moving on to building reusable components to reduce duplication in our code.
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
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:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue.js App</title> </head> <body> <div id="app"> </div> <script src="https://unpkg.com/vue"></script> <script type="text/javascript"> // JS Code here </script> </body> </html>
The main HTML tags and structure should be familiar to you. Let's run over a few of the other aspects.
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:
<div id="app"> </div>
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.
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:
<script src="https://unpkg.com/vue"></script>
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.
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.
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
v-for
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(), "YYYY- MM-ddThh:mm:ss")}}' } ]
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.
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.
