Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Vuex Quick Start Guide
Vuex Quick Start Guide

Vuex Quick Start Guide: Centralized State Management for your Vue.js applications

eBook
€8.99 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Vuex Quick Start Guide

Rethinking User Interfaces with Flux, Vue, and Vuex

I started my first job as a Java EE programmer at the end of 2007. I still remember my friend Giuseppe saying, You don't like JavaScript, do you? and me answering, No, I don't. Each time I write something in JavaScript, it doesn't work in all versions of Internet Explorer... not to mention Firefox! He just replied, Have a look at jQuery. Today, I like to call myself a JavaScript programmer.

Since then, web development has evolved a lot. A number of JavaScript frameworks became popular and then declined because new frameworks emerged. You may think that it is not worth learning new frameworks since they will eventually decline in popularity. Well, in my opinion, that is not true. Each framework added something useful to web development, something that we still use. For example, jQuery made use of JavaScript that was so simple that we started moving client logic to the browser instead of rendering everything server-side.

Today, we write progressive web applications that are complex applications with web user interfaces. This complexity requires discipline and best practices. Fortunately, big companies such as Facebook, Google, and others have introduced frameworks and guidelines to help web programmers. You may have heard about Google's Material Design or Facebook's Flux.

In this chapter we will focus on the following:

  • Model-view-controller (MVC) problems, and using Facebook Flux architecture to solve these problems
  • Flux fundamentals
  • What Vuex is
  • Architectural differences between Flux and Vuex

To understand this book, you need a good knowledge of Vue.js and JavaScript, a basic understanding of ECMAScript 6, and a very basic knowledge of webpack. In any case, almost all the concepts used here, Vuex and otherwise, are explained.

After explaining the Flux concepts, this book will help you understand how Vuex implements these concepts, how to use Vue.js and Vuex to build professional web applications, and finally how to extend Vuex functionality.

MVC problems and the Flux solution

Each time we speak about an application with a user interface, the MVC pattern comes out. But what is the MVC pattern? It is an architectural pattern that divides components into three parts: a Model, a View, and a Controller. You can see the classic diagram describing MVC in the following figure:

Figure 1.0: Classic MVC diagram

Most of the modern frameworks for progressive web applications use the MVC pattern. In fact, if you look at the Vue.js single file component shown in the following figure, you can clearly see the three parts of the MVC pattern:

Figure 1.1: Vue.js single file component

The template and style parts represent the view section, the script part provides the controller, and the data section of the controller is the model.

But what happens when we need some data from the model of a component that's inside another component? Moreover, in general, how can we interconnect all the components of a page?

Clearly, providing direct access to the model of the components from other components is not a good idea. The following screenshot shows the dependencies in the case of exposing the models:

Figure 1.2: MVC hell

Vue.js provides a good way of communicating between parent and child components: You can use Props to pass values from a parent to a child component, and you can emit data from a child component to its parent. The following figure shows a visual representation of this concept:

Figure 1.3: Vue.js parent–child communication

However, when multiple components share a common state, this way of communicating is not enough. The following are the issues that would come up:

  • Multiple views may share the same piece of state
  • User actions from different views may need to change the same piece of state

Some frameworks provide a component called EventBus; in fact, the Vue instance itself is an EventBus. It has two methods: Vue.$emit(event, [eventData]) and Vue.$on(event, callback([eventData])). The following is an example of how to create a global event bus:

// EventBus.js
import
Vue from 'vue';
export const EventBus = new Vue();

// HelloWorldEmitter.js
import { EventBus } from './EventBus.js';
EventBus.$emit('an-event', 'Hello world');

// HelloWorldReceiver.js
import { EventBus } from './EventBus.js';
EventBus.$on('an-event', eventData => {
console.log(eventData);
});

Even with a global event bus, making components communicate is not easy. What if a component that registers to an event gets loaded after the event is fired? It will miss the event. This may happen if that component is inside a module that gets loaded later, which is likely to happen in a progressive web app where modules are lazily loaded.

For example, say that a user wants to add a product to the cart list. She taps on the Add to cart button, which is likely to be in the CartList component, and she expects the product she sees on the screen to be saved in the cart. How can the CartList component find out what the product is that should be added to its list?

Well, it seems that Facebook programmers faced similar problems, and to solve those problems, they designed what they called Flux: Application architecture for building user interfaces.

Inspired by Flux and Elm architecture, Evan You, the author of Vue.js, created Vuex. You may know Redux already. In that case, you will find that Vuex and Redux are similar, and that Evan You saved us time by implementing Vuex instead of forcing every programmer to integrate Redux inside a Vue.js application. In addition, Vuex is designed around Vue.js to provide the best integration between the two frameworks.

But what is Vuex? That is the topic of the next section.

What is Vuex?

Evan You defines Vuex as:

"state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion."

Without knowing Flux, this definition sounds a little bit obscure. Actually, Vuex is a Flux implementation that exploits the reactivity system of Vue using a single, centralized store, and ensures that the state can only be mutated in a predictable fashion.

Before focusing on Vuex itself, we are going to understand the fundamentals of Flux and how Vuex took inspiration from these concepts.

Understanding the Flux fundamentals

Flux is a pattern for managing data flow in your application, and it is the application architecture that Facebook uses for building its web applications. The following diagram shows the structure and data flow in Flux:

Figure 1.4: Structure and data flow in Flux

As shown in the preceding figure, Flux is divided into four parts, and data flows in only one direction. In the next sections, we will see how data flows through the following parts:

  • Actions
  • Dispatchers
  • Stores
  • Views

Although it is important to understand how Flux works, Vuex has its own implementation of Flux architecture that differs from Flux, and it will be explained in detail in the following chapters.

Actions

Actions define the internal API of your application. They represent what can be done, but not how it is done. The logic of state mutation is contained inside stores. An action is simply an object with a type and some data.

Actions should be meaningful to the reader and they should avoid implementation details. For example, remove-product-from-cart is better than splitting it into update-server-cart, refresh-cart-list, and update-money-total.

An action is dispatched to all the stores and it can cause more than one store to update. So dispatching an action will result in one or more stores executing the corresponding action handler.

For example, when a user taps on the Remove from cart button, a remove-product-from-cart action is dispatched:

{type: 'remove-product-from-cart', productID: '21'}

In Vuex, the action system is a bit different, and it splits Flux actions into two concepts:

  • Actions
  • Mutations

Actions represent a behavior of an application, something that the application must do. The result of an action consists typically of one or more mutations being committed. Committing a mutation means executing its associated handler. It is not possible to change the Vuex state directly inside an action; instead, actions commit mutations.

You have to deal with asynchronous code inside actions, since mutations must be synchronous.

Mutations, on the other hand, can and do modify the application state. They represent the application logic directly connected to the application state. Mutations should be simple, since complex behavior should be handled by actions.

Since there is only one store in Vuex, actions are dispatched using the store, and there is a direct connection between an action and its handler. In Flux, on the other hand, every store knows what to do when responding to the action.

You will read about the Vuex action/mutation system in the following chapters. Right now, you just need to understand the concepts behind actions, and that Vuex implements actions in a slightly different way than the one used by Flux.

Dispatcher

There is only one dispatcher per application, and it receives actions and dispatches them to the stores. Every store receives every action. It is a simple mechanism to dispatch actions, and it can handle dependencies between stores by dispatching actions to the stores in a specific order.

For example:

  1. A user taps on the Add to cart button
  2. The view captures this event and dispatches an add-to-cart action
  3. Every store receives this action

Since Vuex differs from Flux because the dispatcher is inside the store, what you should remember here is that every change in the application begins by dispatching an action.

Stores

Stores contain the application state and logic. Stores can be mutated only by actions and do not expose any setter method. There can be more than one store in Flux, each one representing a domain within the application. In Vuex, there is only one store, and its state is called a single state tree. Vuex is not the only framework that enforces the use of a single store: Redux explicitly states that there is one store per Redux application. You may think that a single store may break modularity. We will see later how modularity works on Vuex.

Before switching to Flux architecture, Facebook chat kept experiencing a bug where the number of unread messages was wrong. Instead of having two lists—one of read messages and another of unread ones—they used to derive the number of unread messages from other components events. It is indeed better to have an explicit state where all the information is stored. Think of the state as an application snapshot: You could save it before the application page gets closed and restore it when the application gets opened again so that the user will find the application in the same state it was left in.

There are three important concepts regarding stores:

  • Stores can be mutated only by actions
  • Once a store is mutated, it notifies it has changed to the views
  • Stores represent explicit data, as opposed to deriving data from events

Here is an example of a store reacting to the add-to-cart action dispatched in the previous example:

  1. The store receives the add-to-cart action
  2. It decides it is relevant and executes the logic of the action by adding the current product to the cart product list
  3. It updates its data and then notifies the views that it has changed

Views

Views, or view controllers, display data from the stores. Here is where a framework like Vue.js plugs in.

Rendering data in the stores

In the Facebook video introducing Flux, software engineer Jing Chen talks about some of the problems they faced while developing Facebook Chat, and what lessons they learned. One interesting lesson they learned concerns rendering: They didn't want to rerender all the messages in the chat, but instead wanted to optimize it a bit by updating the chat view with only the new messages. If you are an experienced programmer, you may think, This is a premature optimization. Indeed it is! It is much more simple to pass the whole view-model to the views rather than just pass the differences from the old and new model.

Say that a programmer wants to add a new feature to a view: If the view-model is rendered by the view each time it is modified, they just need to add some properties to the model and add some code to the view to display these new properties. They don't need to worry about updating/rendering logic.

But what about performance? Isn't it bad to rerender the whole page just because the number of unread messages has changed? Here, Vue.js comes to help us. A programmer just needs to update the view-model and Vue.js will understand what has changed and will rerender only the Document Object Model (DOM) parts that actually changed. The following diagram schematizes this concept:

Figure 1.5: Vue.js updating a DOM node

The lesson is this: Spend time on designing explicit, meaningful models and let Vue.js take care of the performance and rendering logic.

The DOM is used to render a web page. See https://www.w3schools.com/js/js_htmldom.asp for more information.

Stores and private components model

Since views display data from stores, you may think that a view-model is just a portion of a store. Actually, each component can have a private model that can hold values that are needed just inside the component. There is no need to put every value in a store. Stores should contain only data relevant to the application.

For example, say you want to select some photos from a list and share them. The view-model of the photo list component will contain the list of selected photos, and when a user taps on the Share button, the view-controller just needs to dispatch an action called share-photos with the selected photo list as data in the action object. There is no need to put the selected photo list inside a store.

Summarizing Flux architecture

The following is the Flux architecture summarized in a single image:

Figure 1.6: Flux data flow explained

Benefits of using Flux

The following are some of the benefits that Facebook gained after introducing Flux to their web applications:

  • Better scalability than the classic MVC
  • Easy-to-understand data flow
  • Easier and more effective unit tests
  • Since actions represent behaviors of the application, behavior-driven development is a perfect match to write applications using Flux architecture

By adding the Vuex framework to your Vue.js application, you will experience the same benefits. In addition, Vuex, like Redux, simplified this architecture in several different ways, such as using a single store per application and removing the dispatcher from the process in favor of using the store to dispatch actions.

Summary

In this chapter, we looked at why Facebook engineers designed the Flux architecture. We focused on the fundamentals of Flux and learned that Vuex differs slightly from Flux. We can now summarize Flux in one sentence: Flux is a predictable state management system with a one-way data flow.

In Chapter 2, Implementing Flux Architecture with Vuex, you will learn the core concepts of Vuex, as well as how you can use Vuex in your applications.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Uncover the hidden features of Vuex to build applications that are powerful, consistent, and maintainable
  • Enforce a Flux-like application architecture in your Vue application
  • Test your Vuex elements and Vue components using Karma/Jasmine testing framework

Description

State management preserves the state of controls in a user interface. Vuex is a state management tool for Vue.js that makes the architecture easier to understand, maintain and evolve. This book is the easiest way to get started with Vuex to improve your Vue.js application architecture and overall user experience. Our book begins by explaining the problem that Vuex solves, and how it helps your applications. You will learn about the Vuex core concepts, including the Vuex store, changing application state, carrying out asynchronous operations and persisting state changes, all with an eye to scalability. You will learn how to test Vuex elements and Vue components with the Karma and Jasmine testing frameworks. You will see this in the context of a testing first approach, following the fundamentals of Test Driven Development. TDD will help you to identify which components need testing and how to test them. You will build a full Vuex application by creating the application components and services, and persist the state. Vuex comes with a plugin system that allows programmers to extend Vuex features. You will learn about some of the most powerful plugins, and make use of the built-in logger plugin. You write a custom Google Analytics plugin to send actions to its analytics API, and an Undo/Redo plugin.

Who is this book for?

If you are a JavaScript developer, working on Vue.js and want to extend your web development skills to develop and maintain bigger applications using state management, then this book is for you. No knowledge of Vuex is required.

What you will learn

  • Moving from classical MVC to a Flux-like architecture
  • Implementing predictable centralized state management in your applications using Vuex
  • Using ECMAScript 6 features for developing a real application
  • Using webpack in conjunction with Vue single file components
  • Testing your Vue/Vuex applications using Karma/Jasmine and inject-loader
  • Simple and effective Test Driven Development
  • Extending your application with Vuex plugins

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 11, 2018
Length: 152 pages
Edition : 1st
Language : English
ISBN-13 : 9781788999939
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Apr 11, 2018
Length: 152 pages
Edition : 1st
Language : English
ISBN-13 : 9781788999939
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 98.97
Full-Stack Web Development with Vue.js and Node
€36.99
Vuex Quick Start Guide
€24.99
Vue.js 2 Design Patterns and Best Practices
€36.99
Total 98.97 Stars icon
Banner background image

Table of Contents

7 Chapters
Rethinking User Interfaces with Flux, Vue, and Vuex Chevron down icon Chevron up icon
Implementing Flux Architecture with Vuex Chevron down icon Chevron up icon
Setting Up Development and Test Environment Chevron down icon Chevron up icon
Coding the EveryNote App Using Vuex State Management Chevron down icon Chevron up icon
Debugging Vuex Applications Chevron down icon Chevron up icon
Using the Vuex Plugin System Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
(2 Ratings)
5 star 0%
4 star 50%
3 star 0%
2 star 50%
1 star 0%
Marcel Thiele Jul 21, 2020
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I really liked the book. There are, however, a few errors, and omissions, in the examples. Especially towards the end of the book (80%).
Amazon Verified review Amazon
larry Mar 24, 2022
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
This book has more information about Flux in the first chapter than Vuex, which is pretty ridiculous. If you don't know Flux, look for another book.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.