Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Vue.js 2 Design Patterns and Best Practices
Vue.js 2 Design Patterns and Best Practices

Vue.js 2 Design Patterns and Best Practices: Build enterprise-ready, modular Vue.js applications with Vuex and Nuxt

By Paul Halliday
AU$53.99
Book Mar 2018 344 pages 1st Edition
eBook
AU$53.99
Print
AU$67.99
Subscription
AU$19.99 Monthly
eBook
AU$53.99
Print
AU$67.99
Subscription
AU$19.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now
Table of content icon View table of contents Preview book icon Preview Book

Vue.js 2 Design Patterns and Best Practices

Chapter 1. Vue.js Principles and Comparisons

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

Prerequisites


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.

Windows

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!

Mac

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.

Installing Node via Homebrew

The quickest way to getHomebrewis 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"

Editor

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.

Browser

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.

Installing the Vue devtools

Head over to the Google Chrome Extensions store and download Vue.js devtools (https://goo.gl/Sc3YU1). After installing this, you'll then have access to the Vue panel within your developer tools. In the following example, we're able to see the data object inside of our Vue instance:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-     
  scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Vue.js</title>
</head>
<body>
  <div id="app"></div>
  <script src="http://unpkg.com/vue"></script>
  <script>
   Vue.config.devtools = true
   new Vue({
     el: '#app',
     data: {
       name: 'Vue.js Devtools',
       browser: 'Google Chrome'
     },
     template: `
      <div>
        <h1> I'm using {{name}} with {{browser}}</h1>
      </div>
     `
   });
  </script>
</body>
</html>

If we then head over to our browser and open up the devtools we can see that Vue has been detected and that our message has outputted on to the screen:

We'll be using this throughout the book to gain extra insight into our applications. Do be aware that the developer tools will only recognize your Vue project if it is served on a local server.

Vue CLI

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.

How Vue.js compares


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

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:

<MyButtoncolor="red"shadowSize={5}>
 ClickMe
</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

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.

In comparison to Angular, Vue looks to enforce a smaller set of constraints and allows the developer more choice. One of Angular's core competencies is TypeScript everywhere. Most developers that came from Angular.js were hearing about TypeScript for the first time when Angular 2 was announced, and I noticed a fair amount of backlash because of the need to "learn a new language". The thing is, JavaScript is TypeScript and the value of increased tooling (autocompletion, refactoring, type safety, and much more) cannot be overlooked.

This is especially true when it comes to working on enterprise projects as the onboarding challenge gets harder with increased project complexity and team size. With TypeScript, we're able to better reason about the relationships between our code at scale. It's this structured development experience that is the prime strength of Angular. This is why the Angular team chose TypeScript as the primary development tool. The benefits of TypeScript are not limited to Angular; we'll be looking at how we can integrate Vue with TypeScript to gain these same benefits later on in the book.

Are there any drawbacks to using Angular as a development framework? Not necessarily. When we're comparing it to Vue, the onboarding experience is vitally different.

Mobile development

When it comes to developing mobile applications, projects such as Angular and React are great choices for developing mobile-first applications. The success of the NativeScript, React Native, and Ionic Framework projects have boosted the significant popularity of these frameworks. For instance, Ionic Framework currently has more stars than Angular on GitHub!

Vue is making waves in this area with projects such as NativeScript Vue, Weex, and Quasar Framework. All of the listed projects are relatively new, but it only takes one to truly spike the popularity of Vue in production even further. Using NativeScript Vue as an example, it only takes 43 lines of code to create a cross-platform mobile application that connects to a REST API and displays the results on screen. If you'd like to follow along with this yourself, run:

# Install the NativeScript CLI
npm install nativescript -g

# New NativeScript Vue project
tns create NSVue --template nativescript-vue-template

# Change directory
cd NSVue

# Run on iOS
tns run ios

Then, we can place the following inside of our app/app.js:

const Vue = require('nativescript-vue/dist/index');
const http = require('http');
Vue.prototype.$http = http;

new Vue({
    template: `
    <page>
        <action-bar class="action-bar" title="Posts"></action-bar>
        <stack-layout>
            <list-view :items="posts">
                <template scope="post">
                    <stack-layout class="list">
                        <label :text="post.title"></label>
                        <label :text="post.body"></label>
                    </stack-layout>
                </template>
            </list-view>
        </stack-layout>
    </page>
    `,    
    data: {
        posts: []
    },
    created(args) {
        this.getPosts();
    },
    methods: {
        getPosts() {
            this.$http
                .getJSON(`https://jsonplaceholder.typicode.com/posts`)
                .then(response => {
                    this.posts = response.map(
                        post => {
                            return {
                                title: post.title,
                                body: post.body
                            }
                        }
                    )
                });
        }
    }
}).$start();

If we then run our code, we can see a list of posts. You'll notice that our Vue code is declarative, and we have the power of larger frameworks at our disposal with much less code:

Server-Side Rendering (SSR)

Server-Side Rendering allows us to take our frontend JavaScript application and render it to static HTML on the server. This is important as it allows us to significantly speed up our application as the browser only has to parse the critical HTML/CSS. Maximizing performance is a key component of modern day web applications and the expectation continues to grow with progressive web applications and projects such as AMP.Both React, Angular and Vue are capable of SSR using a variety of different patterns.

Let's take a look at how we can achieve a simple Server-Side rendered Vue application:

# Create a new folder named vue-ssr:
$ mkdir vue-ssr
$ cd vue-ssr

# Create a new file named server.js
$ touch server.js

# Install dependencies
$ npm install vue vue-server-renderer express

Inside server.js, we can create a new Vue instance and use the Vue renderer to output the content of our instance as an HTML:

const Vue = require("vue");
const server = require("express")();
const renderer = require("vue-server-renderer").createRenderer();

server.get("*", (req, res) => {
  const app = new Vue({
    data: {
      date: new Date()
    },
    template: `
    <div>
    The visited time: {{ date }}
    </div>`
  });

  renderer.renderToString(app, (err, html) => {
    if (err) {
      res.status(500).end("Internal Server Error");
      return;
    }
    res.end(`
      <!DOCTYPE html>
      <html lang="en">
        <head><title>Hello</title></head>
        <body>${html}</body>
      </html>
    `);
  });
});

server.listen(8080);

To run the application, type the following in the Terminal:

$ node server.js

We can then open this in our browser at http://localhost: 8080 and we'd see the current date and time on screen. This is a simple example but we were able to see our application rendered using the vue-server-renderer. Notice how we're not defining a target element to render content within our Vue instance; this is handled by the renderer.renderToString function.

You'll also notice that we have the data-server-rendered="true" attribute on our DOM node, which isn't present on a client-side rendered Vue application. This allows us to hydrate our client-side instance with our server-side instance, something we'll be looking at more detail in the later chapter(s) on Nuxt (https://nuxtjs.org/).

Conclusion

The choice of web framework in the enterprise is always going to be dependent on the goals of your project, team, and organizational priorities. No one framework is the correct choice, because optimal means different things depending on the context.Each framework or library has its own unique benefits, drawbacks, and priorities. If your priority is to create web applications quickly and at scale, Vue can compete with the other market solutions.

Vue is feature rich, declarative, and highly legible. Even though it's a simplistic framework, the declarative nature of Vue allows us to get up and running at blazing fast speed without having to worry about overly complex patterns.

Summary


In this chapter, we looked at how we can set up our development environment and how Vue is being used in many products throughout the industry. We've learned that Vue is a simple, yet powerful frontend development framework. As well as this, we've considered how Vue shapes up when compared to other popular projects, such as Angular and React. We've also looked at how Vue works with other technologies, such as NativeScript, to create cross-platform native mobile applications. Finally, we've investigated SSR at a high level and set the stage for chapters to come. Hopefully, by now you're convinced that Vue is worth learning, and you're looking forward to taking advantage of all it has to offer!

In the next chapter, we'll be looking at the Vue CLI and how to take advantage of tools such as Webpack to create our Vue projects. As well as this, we'll look at how to take advantage of static types and tooling with TypeScript and reactive observable patterns with RxJS within Vue.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • Craft highly modular applications by exploring design patterns and the component architecture of Vue.js
  • • Enforce a Flux-like application architecture in your Vue.js applications with Vuex
  • • Easy-to-follow examples that can be used to create reusable code and extensible designs

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 learn

• Understand the theory and patterns of Vue.js • Build scalable and modular Vue.js applications • Take advantage of Vuex for reactive state management • Create single page applications with vue-router • Use Nuxt for FAST server-side rendered Vue applications • Convert your application to a Progressive Web App (PWA) and add ServiceWorkers and offline support • Build your app with Vue.js by following best practices and explore the common anti-patterns to avoid

Product Details

Country selected

Publication date : Mar 14, 2018
Length 344 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781788839792
Category :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Mar 14, 2018
Length 344 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781788839792
Category :

Table of Contents

19 Chapters
Title Page Chevron down icon Chevron up icon
Copyright and Credits Chevron down icon Chevron up icon
Packt Upsell Chevron down icon Chevron up icon
Contributors Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
1. Vue.js Principles and Comparisons Chevron down icon Chevron up icon
2. Proper Creation of Vue Projects Chevron down icon Chevron up icon
3. Writing Clean and Lean Code with Vue Chevron down icon Chevron up icon
4. Vue.js Directives Chevron down icon Chevron up icon
5. Secured Communication with Vue.js Components Chevron down icon Chevron up icon
6. Creating Better UI Chevron down icon Chevron up icon
7. HTTP and WebSocket Communication Chevron down icon Chevron up icon
8. Vue Router Patterns Chevron down icon Chevron up icon
9. State Management with Vuex Chevron down icon Chevron up icon
10. Testing Vue.js Applications Chevron down icon Chevron up icon
11. Optimization Chevron down icon Chevron up icon
12. Server-Side Rendering with Nuxt Chevron down icon Chevron up icon
13. Patterns Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Top Reviews
No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.