Reader small image

You're reading from  Vue.js 2 Cookbook

Product typeBook
Published inApr 2017
Reading LevelBeginner
PublisherPackt
ISBN-139781786468093
Edition1st Edition
Languages
Right arrow
Author (1)
Andrea Passaglia
Andrea Passaglia
author image
Andrea Passaglia

Andrea Passaglia was born in Genoa, in northern Italy. Interested about technology since his parents gave him a toy computer when he was a boy, he started studying web technologies at an early age. After obtaining his master's degree in computer engineering he worked on the design and implementation of web interfaces for companies of various sizes and in different industries (healthcare, fashion, tourism, and transport). In 2016 he moves in the silicon valley of Europe to tackle new problems in the banking industry at the Edgeverve Dublin Research and Development Labs. A backend technologist by trade, Vue.js is his first tool to bring to life his creations when it comes to the frontend. Andrea is married to a lovely Russian girl from Siberia and they often cook together mixing culinary traditions.
Read more about Andrea Passaglia

Right arrow

Chapter 10. Large Application Patterns with Vuex

In this chapter, we'll cover the following recipes:

  • Dynamically loading pages in your vue-router
  • Building a simple storage for the application state
  • Understanding Vuex mutations
  • Listing your actions in Vuex
  • Separating concerns with modules
  • Building getters to help retrieve your data
  • Testing your store

Introduction


In this chapter, you will learn how Vuex works and how to use it to support a scalable application. Vuex implements a pattern that is popular in frontend frameworks and consists of dividing the different concerns to manage a big global application state. The mutations are the only things that can change the state, so you have only one place to look for that. Much of the logic, along with all the asynchronous logic, is contained in the actions; finally, getters and modules further help to spread the cognitive load when it comes to computing the derived state and splitting your code into different files.

Along with recipes, you will find grains of wisdom that I found useful when developing real large applications; some have to do with naming conventions and others with little tricks to avoid bugs.

If you complete all the recipes, you will be ready to develop big frontend applications with fewer bugs and seamless collaboration.

Dynamically loading pages in your vue-router


Soon, you will build huge Vue websites with loads of components. Loading a lot of JavaScript may generate wasteful and useless upfront delay. In the Loading your components asynchronously recipe in Chapter 4, All About Components, we already saw a hint of how to retrieve our components remotely. Here we will apply a similar technique to components loaded by a route in vue-router.

Getting ready

This recipe requires knowledge of vue-router. If you want, you can go through Loading your components asynchronously in Chapter 4, All About Components, to get a better idea of what is happening.

How to do it...

Create a new project with vue-cli by making a new directory and running the following command:

vue init webpack

You can answer the question as you prefer, as long as you add the vue-router to the template when asked.

We will create two components: one will be our home page and it will be small and light, the other component will be very big and very slow...

Building a simple storage for the application state


In this recipe, you will understand the fundamentals of Vuex when building a big application. This recipe is a little unorthodox because to understand how Vuex's store work, we will manipulate it directly; you should never do that in a real application.

Getting ready

Before trying this recipe, you should complete Making two components talk with Vuex in Chapter 4All About Components.

 

How to do it...

Create a new project based on the Webpack template with the following command run in a new directory:

vue init webpack

How you answer the question is not relevant. Run npm intall and install Vuex with npm install vuex --save or yarn add vuex if you use yarn. 

Open the  main.js file inside the src folder and add the following highlighted lines to finish installing Vuex:

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'

/* eslint-disable no-new */
new Vue({
 el: '#app',
 router,
 store,
 template...

Understanding Vuex mutations


The proper way to mutate the state in a Vuex application is with the help of mutations. Mutations are a very useful abstraction to decompose state changes in the atomic unit. In this recipe, we will explore just that.

Getting ready

This recipe can be completed without knowing too much about Vuex, but completing the previous recipe first is suggested.

How to do it...

Add Vuex as a dependency to your project (the CDN address is https://unpkg.com/vuex). I will assume that you are using JSFiddle to follow along; otherwise, just remember to put Vue.use(Vuex) before the store code.

The sample application we will build is to broadcast notifications to the users of the website.

The HTML layout looks as shown:

<div id="app">
  <div v-for="(message, index) in messages"> 
    <p style="cursor:pointer">{{message}}
      <span @click="close(index)">[x]</span>
    </p>
  </div>
  <input v-model="newMessage" @keyUp.enter="broadcast">...

Listing your actions in Vuex


All your mutations must be synchronous, so how do you do things such as waiting for a timeout or using Axios for an AJAX request? Actions are the next level of abstraction that will help you with this. Inside an action, you can commit multiple mutations and make asynchronous operations.

 

Getting ready

Mutations are the building blocks of actions, so it's highly suggested you complete the preceding recipe before trying this.

We will be using the setup from the Building a simple storage for the application state recipe; you can use your own as well, but in any case this recipe is based on a slight modification of the official Webpack template.

How to do it...

You will build a clone of the popular Xkcd website. Actually, it will be a wrapper more than a real clone, since we will reuse the panels from the website.

Create a Vue project based on the Webpack template with vue init webpack. The first thing we will do is wire up the API to the Xkcd website in the index.js inside...

Separating concerns with modules


When building big applications, the Vuex store can become crowded. Luckily, it's possible to divide the different concerns of the applications into separate compartments with modules.

Getting ready

This recipe can be a reference if you want to use modules. You are expected to already know enough about Vuex.

For this recipe, you will have to be a little familiar with Webpack.

How to do it...

In this recipe, we will model a fully functional human body in a slightly simplified manner. Every organ will have a separate module. Create a new Webpack template with vue init webpack and npm install vuex. Create a new directory with the src/store/index.js file in it. Inside, write the following:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    brain,
    heart
  }
})

export default store

The heart module is like this; put it before the store declaration:

const heart = {
  state: { loves: undefined },
  mutations...

Building getters to help retrieve your data


You don't want to keep too much data in your state. It can be especially dangerous to keep duplicate or derivative data because it can be brought out of sync very easily. Getters help you with this without shifting the burden onto the components by keeping all the logic in one place.

Getting ready

This recipe is for you if you already have some Vuex knowledge and want to expand your horizons.

How to do it...

Imagine that you are building a Bitcoin wallet. You want to give your users an overview of their balance, and you want them to see how many Euros it corresponds to. Create a new Webpack template with vue init webpack and npm install vuex. Create a new src/store/index.js file and write the following inside it:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    bitcoin: 600,
    rate: 1000,
    euro: 600000
  }
})

export default store

This code is prone to errors. The first error can be a miscalculation...

Testing your store


As you know from Chapter 7Unit Testing and End-To-End Testing, testing is the most important part of professional software. As the store often defines the business logic of your application, testing it may be vital for your application. In this recipe, you will write tests for a Vuex store.

Getting ready

This recipe requires knowledge from Chapter 7Unit Testing and End-To-End Testing and familiarity with Vuex; you can get it from the earlier recipes of this chapter.

How to do it...

First, I'll define some features that our store must implement; then you will write tests that prove that the features are present and working.

Software requirements

Our store consists of items in a to-do list, like the following:

state: {
  todo: [
    { id: 43, text: 'Buy iPhone', done: false },
    ...
  ],
  archived: [
    { id: 2, text: 'Buy gramophone', done: true },
    ...
  ]
}

We have two requirements:

  • We must have an MARK_ITEM_AS_DONE mutation that changes the done field from false to...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Vue.js 2 Cookbook
Published in: Apr 2017Publisher: PacktISBN-13: 9781786468093
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Andrea Passaglia

Andrea Passaglia was born in Genoa, in northern Italy. Interested about technology since his parents gave him a toy computer when he was a boy, he started studying web technologies at an early age. After obtaining his master's degree in computer engineering he worked on the design and implementation of web interfaces for companies of various sizes and in different industries (healthcare, fashion, tourism, and transport). In 2016 he moves in the silicon valley of Europe to tackle new problems in the banking industry at the Edgeverve Dublin Research and Development Labs. A backend technologist by trade, Vue.js is his first tool to bring to life his creations when it comes to the frontend. Andrea is married to a lovely Russian girl from Siberia and they often cook together mixing culinary traditions.
Read more about Andrea Passaglia