28,99 €
Become an expert Vue developer by understanding design patterns and the component architecture of Vue.js to write clean and maintainable code
Key FeaturesCraft highly modular applications by exploring design patterns and the component architecture of Vue.jsEnforce a Flux-like application architecture in your Vue.js applications with VuexEasy-to-follow examples that can be used to create reusable code and extensible designsBook Description
Vue.js 2 Design Patterns and Best Practices starts by comparing Vue.js with other frameworks and setting up the development environment for your application, and gradually moves on to writing and styling clean, maintainable, and reusable Vue.js components that can be used across your application. Further on, you'll look at common UI patterns, Vue form submission, and various modifiers such as lazy binding, number typecasting, and string trimming to create better UIs. You will also explore best practices for integrating HTTP into Vue.js applications to create an application with dynamic data. Routing is a vitally important part of any SPA, so you will focus on the vue-router and explore routing a user between multiple pages. Next, you'll also explore state management with Vuex, write testable code for your application, and create performant, server-side rendered applications with Nuxt. Toward the end, we'll look at common antipatterns to avoid, saving you from a lot of trial and error and development headaches.
By the end of this book, you'll be on your way to becoming an expert Vue developer who can leverage design patterns to efficiently architect the design of your application and write clean and maintainable code.
What you will learnUnderstand the theory and patterns of Vue.jsBuild scalable and modular Vue.js applicationsTake advantage of Vuex for reactive state managementCreate single page applications with vue-routerUse Nuxt for FAST server-side rendered Vue applicationsConvert your application to a Progressive Web App (PWA) and add ServiceWorkers and offline supportBuild your app with Vue.js by following best practices and explore the common anti-patterns to avoidWho this book is for
This book is for Vue developers who are familiar with framework design principles and utilize commonly found design patterns in developing web applications.
Paul Halliday (BSc Hons) is a developer advocate with a focus on fast-moving 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 expertize in NativeScript and Kendo UI.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 254
Veröffentlichungsjahr: 2018
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 author 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.
Commissioning Editor: Kunal ChaudhariAcquisition Editor: Shweta PantContent Development Editor: Flavian VazTechnical Editor: Diksha WakodeCopy Editor: Safis EditingProject Coordinator: Devanshi DoshiProofreader: Safis EditingIndexer: Aishwarya GangawaneGraphics: Jason MonteiroProduction Coordinator: Shraddha Falebhai
First published: March 2018
Production reference: 1080318
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78883-979-2
www.packtpub.com
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.
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
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.
Paul Halliday (BSc Hons) is a developer advocate with a focus on fast-moving 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 expertize in NativeScript and Kendo UI.
Pablo Henrique is a frontend developer, speaker, writer, and community leader focused on helping companies and individuals succeed with their frontend applications. His current job as a Squad Leader at a Brazilian company gave him the opportunity to lead several developers' teams and to see the benefits of Vue.js while creating products and services. He has given many presentations about Vue.js and has also reviewed Vue.js 2.x by Example, written by Mike Street.
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.
Title Page
Copyright and Credits
Vue.js 2 Design Patterns and Best Practices
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Vue.js Principles and Comparisons
Prerequisites
Windows
Mac
Installing Node via Homebrew
Editor
Browser
Installing the Vue devtools
Vue CLI
How Vue.js compares
React
Angular
Mobile development
Server-Side Rendering (SSR)
Conclusion
Summary
Proper Creation of Vue Projects
Visual Studio Code extensions
Vetur
Vue 2 Snippets
Vue CLI
JavaScript modules
Vue-loader
Loading modules without Webpack
VueJS devtools
TypeScript and Vue
Lifecycle hooks
Properties
Computed
RxJS and Vue
What is RxJS?
Integrating with Vue
Summary
Proxying
How 'this' works within JavaScript
How Vue handles 'this'
Data properties
Computed properties
Watched properties
Lifecycle hooks
Vue.js and the Virtual DOM
DOM
Virtual DOM
Summary
Writing Clean and Lean Code with Vue
Proxying
How 'this' works within JavaScript
How Vue handles 'this'
Data properties
Computed properties
Watched properties
Lifecycle hooks
Vue.js and the Virtual DOM
DOM
Virtual DOM
Summary
Vue.js Directives
Model
Iteration with v-for
Bindings
Adding secondary properties
Style bindings
DOM events and v-on
Key modifiers
Event modifiers
Conditionally showing DOM elements
v-show
v-if
v-else
v-else-if
Filters
Locally registered filters
Globally registered filters
Summary
Secured Communication with Vue.js Components
Your first Vue component
Registering components globally
Scoped styles
Registering a component locally
Component communication
Configuring property values
Custom events
Sending event values
Event Bus
Slots
Defaults
Named slots
Summary
Creating Better UI
Animations
CSS animations
Animate.css
Using Animate.css
Transitions
Transition states
Form validation
What is Vuelidate?
Using Vuelidate
Displaying form errors
Password validation
Form submission
Render/functional components
Rendering elements
Attributes
Components and props
JSX
Summary
HTTP and WebSocket Communication
HTTP
Installing JSON server
HTTP GET
HTTP POST
HTTP PUT
HTTP DELETE
Real-time chat application with Node and Socket.io
What is Socket.io?
Server setup
Client connections
Setting up Vue and Socket.io
Determining connection status
Creating a connection status bar
Navigation bar
Message list
Adding messages to the list
Server-side events with Socket.io
Nodemon
Summary
Vue Router Patterns
Single Page Applications
Using the router
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
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
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
Testing Vue.js Applications
Why testing?
Unit testing
Setting up vue-test-utils
Creating a TodoList
Writing tests
Vue options
Adding new features
Click events
Testing events
Using Wallaby.js for a better testing experience
Summary
Optimization
Progressive Web Applications (PWAs)
Web application manifest
Testing on a device
Firebase deployment
Continuous Integration (CI)
Unit tests
Creating a Git repository
Connecting to Travis CI
Configuring Travis
Automatic deployment to Firebase
Service worker
Summary
Server-Side Rendering with Nuxt
Nuxt
Creating a Nuxt project
Directory structure
Nuxt configuration
Navigation
Navigating between routes
Layouts
The Mock REST API
asyncData
Categories
Category detail
Error page
Plugins
Adding recipes
Transitions
Building for production
Static
SPA mode
Summary
Patterns
Components
Communication – Anti-pattern
What can we change about this to make it better?
Children mutating props – Anti-pattern
What should we do instead?
Mutating property arrays
Using data as an object - Anti-Pattern
Naming components – Anti-pattern
Template expressions
Pattern – Container/Presentational components
Prop validation
Understanding reactivity
Summary
Vue.js is a JavaScript framework that allows you to create performant web applications. It boasts a smaller learning curve than its competitors and has detailed documentation with a variety of examples and use cases. Vue.js applications can be created with the Vue CLI or by including it in your page via a script tag, making it super-easy to use in projects without build systems.
In a similar way to other modern web frameworks/libraries, Vue.js is component driven, and this means that you can create self-contained units with their own view/data logic. This allows our application to scale as it gets larger because any changes can be encapsulated away from each other.
When scaling your application, state management is a hot topic in the frontend space, and Vue.js solves this with the Vuex library. This allows us to define actions within our application and act accordingly, giving us predictable state that can be used to form the basis of our user interface and other interactions.
This book explores all this and more, and it provides examples of how these principles can be implemented into new and old Vue.js applications.
This book is for people interested in creating web and mobile applications with JavaScript. Prior experience with HTML5/ES2015 will be helpful, as modern JavaScript concepts are used within the book. You'll likely be looking to make use of this knowledge to create interactive web-based experiences within your personal projects or job role.
Chapter 1, Vue.js Principles and Comparisons, introduces the readers to Vue.js and motivates them to use it as a framework to create web applications. The reader will gain an understanding of the differences between Vue.js in comparison to other popular frameworks, such as React and Angular.
Chapter 2, Proper Creation of Vue Projects, looks at the appropriate way to create a Vue project. This includes the use of Webpack, Babel/TypeScript (for ES6), .vue files, linting, and more.
Chapter 3, Writing Clean and Lean Code with Vue, takes a deeper look at the Vue.js instance and different reserved properties, such as data, computed, and watch, as well as creating getters and setters. This chapter especially considers when to use computed properties and when to use watched properties. It also outlines why templates should be kept especially lean for easier maintenance.
Chapter 4, Vue.js Directives, introduces the fact that the developers have access to a powerful set of directives, such as v-for, v-if, v-model, and others when writing reactive Vue applications. This chapter looks at each directive in detail, as well as best practices and patterns. Furthermore, the reader is introduced to using shorthand syntax for event binding.
Chapter 5, Secured Communication with Vue.js Components, takes a more advanced look at Vue components, with a look at component communication. We’ll take a look at passing properties, as well as validating for prop types and considering the different types of properties and data flows.
Chapter 6, Creating Better UI, focuses on the common UI patterns of Vue. It takes another look at how v-model can be used to gain input from the user, along with a glance at binding to inputs such as text, checkbox, radio buttons, and so on. It also looks at drop-down and dynamic inputs. Finally, the chapter covers form submission and various modifiers, such as lazy binding, number typecasting, and string trimming.
Chapter 7, HTTP and WebSocket Communication, covers the best practices for integrating HTTP into Vue.js applications. It takes a look at Axios and a variety of methods for sending HTTP requests (that is, root instance/component/ nav guards). This chapter also takes a look at using socket.io, along with the creation of a basic Node/ Express API for real-time integration.
Chapter 8, 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 9, 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 Vue-devtools to capture actions and Vue instance data.
Chapter 10, Testing Vue.js Applications, demonstrates that testing is a vital part of any project, regardless of the framework or language. This chapter looks at testing our application and how to write testable code. We'll then look at testing our application with Jasmine and Karma, as well as testing our Vuex code when testing mutations.
Chapter 11, Optimization, outlines deploying a Vue application and any potential performance optimizations. It then looks at converting an application to a Progressive Web App (PWA) and adding ServiceWorkers, offline support, and more. It also looks at ways in which the overall bundle size can be reduced, and at performance wins with SVG.
Chapter 12, Server-Side Rendering with Nuxt, showcases using Nuxt to create Vue applications that are server-side rendered. The project will be created by using the Vue CLI, and we’ll look at everything from configuration to routing, middleware, and testing Nuxt, all the way through to deployment.
Chapter 13, Patterns, assists the reader with common anti-patterns and allows them to avoid these principles when writing Vue.js applications. A style guide is proposed, as well as key issues such as the use of $parent, $ref coupling issues, inline expressions, and others.
You should already have an understanding and knowledge of JavaScript (ES2015+), as well as HTML5 and CSS3.
Experience with Vue.js is not required for this book, although experience with other JavaScript frameworks will assist with comparisons and similar features.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.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/Vue.js-2-Design-Patterns-and-Best-Practices.
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 a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/Vuejs2DesignPatternsandBestPractices_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in the text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."
A block of code is set as follows:
// my-module.jsexport default function add(x, y) { return x + y}
Any command-line input or output is written as follows:
$ npm install
$ npm run dev
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
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.packtpub.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 [email protected] 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.
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 packtpub.com.
In this chapter, we'll be looking at why Vue is an important web development framework, as well as looking at setting up our development environment. If we're looking to use Vue for our next project, it's important we realize the implications, time investment, and learning curve when doing so. You'll have considered how Vue shapes up to other frontend development projects, as well as creating your first application with Vue.
In summary, we'll be considering the following points:
Downloading the book prerequisites
Understanding of where Vue fits into a frontend framework
Why you should consider using Vue as the framework for your next project
Investigation of how flexible Vue is and its role in mobile development
Although you could develop Vue applications without Node, we'll be using Node.js throughout this book to manage dependencies and interact with the Vue Command Line Interface (CLI). This allows us to bootstrap projects quicker and gives us a better development experience as we can use ECMAScript 2015 by default. Let's have a quick refresher on setting up your development environment.
Installing Node for Windows is as simple as visiting https://nodejs.org and downloading the latest version. Ensure that when following the installation steps, Add to PATH is selected as this will allow us to access node commands within our Terminal.
Once you've done that, check your Node installation works by typingnode-vandnpm-v. If you get two version numbers back (that is, one for each), then you're ready to go ahead with the rest of the book!
Installing Node for Mac involves a little more work than simply downloading the installer from the Node website. While it is possible to use the installer from https://nodejs.org,it is not advised due to the requirement ofsudo.
If we did it this way, we'd have to prefix all of ournpmcommands withsudoand this can leave our system vulnerable to potential scripting attacks and is inconvenient. Instead, we can install Node via the Homebrew package manager and we can then interact with npm without worrying about having to run things assudo.
Another great thing about using Homebrew to install Node is that it's automatically added to our PATH. This means we'll be able to type node commands without having to fiddle around with our environment files.
The quickest way to get Homebrew is to visit http://brew.sh and get hold of the installation script. It should look a little something like this:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Simply paste that into your Terminal and it'll download the Homebrew package manager to your Mac. We can then use brew install node to install Node on our system without any worries.
Once you've done that, check your Node installation works by typing node -v and npm -v. If you get two version numbers back (that is, one for each), then you’re ready to go ahead with the rest of the book!
In order to manage the different Node versions, we could also install the Node Version Manager (NVM). Do note however that this is currently only supported by Mac at present and not Windows. To install NVM, we can use Homebrew like so:
--use Brew to install the NVM
brew install nvm
--File directory
mkdir ~/.nvm
--Install latest version
nvm install --lts
--Ensure latest version is used
nvm use node
--Remember details across sessions
nano ~/.bash_profile
--Execute in every session
export NVM_DIR="$HOME/.nvm"
. "$(brew --prefix nvm)/nvm.sh"
A variety of editors can be used, such as Visual Studio Code, Sublime Text, Atom, and WebStorm. I recommend Visual Studio Code (https://code.visualstudio.com) as it has a frequent release cycle and a wealth of Vue extensions that we can use to improve our workflow.
We will be using Google Chrome to run our project(s) as this has an extension named Vue devtools that is instrumental to our development workflow. If you do not use Google Chrome, ensure your browser has the same Vue devtools extension that is available for usage.
To take advantage of all of the features of Vue, we'll be using Vue CLI. This allows us to create projects with various starter templates with appropriate bundling/transpilation configurations. Type the following into your Terminal ensuring Node is installed:
$ npm install vue-cli -g
This sets us up for the future sections as using starter templates significantly empowers our workflow.
This book seeks to outline how to best structure your Vue applications with common development patterns, best practices, and anti-patterns to avoid.
Our journey starts by taking a look at how Vue shapes up to other common projects, and if you measure your frameworks by GitHub stars, Vue is clearly a future winner. According to https://bestof.js.org, in 2017 it currently measures at 114 stars per day in comparison to React's 76 and Angular's 32.
Framework discussion when talking about modern web development technologies is an interesting one. Very rarely do you find a true, unbiased comparison... but that's fine! It's not about which framework or library is best, but rather what's best for your team, project goals, consumers, and hundreds of other variables. As a Vue developer, you're likely a person that wants to build reactive web applications with a simple, easy-to-use API.
It's this adaptable, easy-to-use API that makes Vue pleasant to work with, and perhaps one of the strongest points of Vue is the simple, focused documentation. It has a significantly low barrier to entry: simply add a script file from a CDN, initialize a new Vue instance... and you're away! Granted, there's much more to Vue than this, but in contrast to some fully fledged frameworks such as Angular, you'd be forgiven for thinking it's that easy.
Vue uses templates, declarative bindings, and a component-based architecture to separate concerns and make projects easier to maintain. This becomes especially important when considering which framework to use inside of an enterprise. Usually, this is where projects such Angular shine as it's ability to enforce standards across the entire project.
We've established it's easy to use, but Vue is quite young in comparison to its competitors... how do we know it's not all hype? Is it being used in production by anyone? It certainly is! GitLab recently wrote an article about why they chose Vue.js (https://about.gitlab.com/2016/10/20/why-we-chose-vue/), and the primary benefits they cited were ease of use, less code, and fewer assumptions. Other companies such as Laravel, Nintendo, Sainsbury's and Alibaba are all following this route and even companies such as Rever Shine rewrote their web client from Angular 2.x to Vue 2.x (https://medium.com/reverdev/why-we-moved-from-angular-2-to-vue-js-and-why-we-didnt-choose-react-ef807d9f4163).
It's not just public – facing web applications that are taking advantage of Vue.js—NativeScript Sidekick (https://www.nativescript.org/blog/announcing-the-nativescript-sidekick-public-preview), a project focused on improving the NativeScript development experience, is built with Electron and Vue.js.
If we gain some insights from the State of JavaScript survey (http://2016.stateofjs.com/2016/frontend/) by Sacha Greif (https://twitter.com/SachaGreif) and Michael Rambeau (http://michaelrambeau.com/), we can see that a whopping 89% of people used Vue before and want to use it again. Other libraries such as React have similar satisfaction rates at 92%, but Angular 2 and onwards didn't see anywhere near as much love, with 65% wanting to use it again:
What other options are available to us as frontend developers? How do they shape up to Vue? Let's start with React.
React is a JavaScript library developed and maintained by Facebook, and is largely the closest comparison to Vue as their goals are very similar. Like Vue, React is component based and takes advantage of Virtual DOM concepts. This allows for performant rendering of DOM nodes, as a different algorithm is used to determine which parts of the DOM have changed and how best to render/update them on change.
When it comes to templates, React uses JSX to render items on the screen. It takes the more verbose way of creating DOM elements with React.createElement and simplifies it like so:
This is how it will look without JSX:
React
.
createElement</span>
(
MyButton
,
{
color
:
'red'
,
shadowSize
:
5
},
'Click Me'
)
Here is how it will look with JSX. As you can see, the two appear very different from one another:
<
MyButton
color
"red"
shadowSize
{5
}
>
Click
Me
<
/MyButton>
For newer developers, this adds a slight learning overhead when compared to Vue's simple HTML template, but it is also what gives React its declarative power. It has a state management system using setState(), but also has compatibility with third-party state containers such as Redux and MobX. Vue also has similar capabilities with the Vuex library, and we'll be looking at this in further detail in later sections of this book.
One of the common recent concerns of using React is the BSD + Patents license agreement, something to keep in mind if you're part of an enterprise. Due to this license, Apache recently declared that no Apache software products will use React. Another example of this is the announcement by Wordpress.com that they're no longer using React for their Gutenberg project (https://ma.tt/2017/09/on-react-and-wordpress/). This doesn't necessarily mean that you shouldn't use React in your projects, but is worth pointing out nonetheless.
Some concerned developers elect to use alternatives such as Preact but more recently Vue.js, as it meets a lot of the goals that React developers are looking for when developing applications. To that end, Microsoft (http://dev.office.com/fabric#/components), Apple (https://developer.apple.com/documentation), and countless other companies have products released with React – make of that what you will.
Angular is an opinionated JavaScript framework developed and maintained by Google. At the time of writing, it's currently approaching version 5 and offers a structured standards-based approach to web development. It uses TypeScript to enforce type safety and ECMAScript 2015 > support.