Book Image

Vue.js 2 Design Patterns and Best Practices

By : Paul Halliday
Book Image

Vue.js 2 Design Patterns and Best Practices

By: Paul Halliday

Overview of this book

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.
Table of Contents (19 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
Free Chapter
1
Vue.js Principles and Comparisons
12
Server-Side Rendering with Nuxt
Index

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.