Free eBook - Vue.js 2 Design Patterns and Best Practices

4.8 (4 reviews total)
By Paul Halliday
  • A new free eBook every day on the latest in tech
  • 30 permanently free eBooks from our core tech library
  1. Vue.js Principles and Comparisons

About this book

This book starts off by comparing Vue.js with other frameworks and setting up the development environment for your application. It gradually moves on to writing and styling clean, maintainable, and reusable components that can be used across your application.

Moving 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 route 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.

Towards the end we'll look at common anti-patterns to avoid, to save you from a lot of trial and error and development headaches.

By the end of this book, you'll be well 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.

Publication date:
March 2018
Publisher
Packt
Pages
344
ISBN
9781788839792

 

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.

About the Author

  • Paul Halliday

    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 expertise in NativeScript and Kendo UI.

    Browse publications by this author

Latest Reviews

(4 reviews total)
Useful in practice, well presented
Good written book. Learn new things from the book.
one section of the book has a double entry. This was reported and will be corrected. The support appriciated the note on the double entry

Recommended For You

Complete Vue.js 2 Web Development

Become a pro in creating modern interactive web applications using this JavaScript framework

By Mike Street and 2 more
Building Forms with Vue.js

Learn how to build dynamic schema-driven forms with Vue from scratch

By Marina Mosti
Vue.js: Understanding its Tools and Ecosystem

Explore one of the fastest-growing frameworks in the front-end development

By Dave Berning
Vue CLI 3 Quick Start Guide

Build Vue apps the right way using Vue CLI 3. Understand how the building blocks of Vue CLI 3 work including npm, webpack, babel, eslint, plugins, GUI, testing, and SCSS. Import third-party libraries and maintain your project.

By Ajdin Imsirovic