Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Front-End Development Projects with Vue.js

You're reading from  Front-End Development Projects with Vue.js

Product type Book
Published in Nov 2020
Publisher Packt
ISBN-13 9781838984823
Pages 774 pages
Edition 1st Edition
Languages
Authors (5):
Raymond Camden Raymond Camden
Profile icon Raymond Camden
Hugo Di Francesco Hugo Di Francesco
Profile icon Hugo Di Francesco
Clifford Gurney Clifford Gurney
Profile icon Clifford Gurney
Philip Kirkbride Philip Kirkbride
Profile icon Philip Kirkbride
Maya Shavin Maya Shavin
Profile icon Maya Shavin
View More author details

Table of Contents (16) Chapters

Preface
1. Starting Your First Vue Project 2. Working with Data 3. Vue CLI 4. Nesting Components (Modularity) 5. Global Component Composition 6. Routing 7. Animations and Transitions 8. The State of Vue.js State Management 9. Working with Vuex – State, Getters, Actions, and Mutations 10. Working with Vuex – Fetching Remote Data 11. Working with Vuex – Organizing Larger Stores 12. Unit Testing 13. End-to-End Testing 14. Deploying Your Code to the Web Appendix

9. Working with Vuex – State, Getters, Actions, and Mutations

Overview

In this chapter, you will learn how to use Vuex to build more complex Vue applications. You'll learn the specifics concerning how to add Vuex to a Vue application, how to define state with the Vuex store, and then use getters, actions, and mutations to read data from, and update it in, the store. By the end of the chapter, you will have seen multiple examples of how Vuex transforms your Vue applications, preparing them to grow much more complex in a much more manageable fashion.

Introduction

In the previous chapter, you learned how to use the Event Bus pattern to help solve an important problem: communicating events back and forth between complex and highly nested sets of components. The Event Bus pattern provided a simple pub and sub system by which any component could emit an event and any component could then listen to that event as well. While writing your own solution to this problem is a great way to keep your coding skills sharp, it would be better, in this case, to use an already developed, well-tested solution already in use in the Vue community—Vuex (https://vuex.vuejs.org/):

Figure 9.1: The Vuex home page

Vuex is a core part of the Vue ecosystem and provides what we already built in the previous chapter along with much more. Let's take a high-level look at the main features of Vuex.

Store

At a high level, a Vuex instance, or one use of Vuex, is considered a store. The store is the top-level container employing...

Installing Vuex

There are two main methods of using Vuex, depending on the type of Vue application you're building. If you are not using the CLI to scaffold out an application and simply added Vue via a script tag, you can include Vuex the same way. Assuming you've downloaded both Vue and Vuex to a folder named js, you would load them both like so:

<script src="js/vue.js"></script>
<script src="js/vuex.js"></script>

You can also load both Vue and Vuex via Content Delivery Networks (CDNs):

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>

Note

It is important that Vuex is loaded after Vue. Doing so makes Vuex available to your Vue code without any other configuration.

If you created an application using the CLI, remember first that the CLI itself will prompt you during creation if you want to add Vuex:

...

Working with State

At the lowest level in a Vuex store, you will find the actual data (the state) that Vuex manages. All components have access to the state via a special $store variable. While there's more within this variable, to read the state, you can use $store.state.someStateValue. So, for example: Hello, my name is {{ $store.state.name }} would output the name value from your Vuex store in a component. For simple operations reading from the store, that's all you need.

We will now learn how to display state values in the following exercise.

Exercise 9.01: Displaying State Values

In this exercise, you will create an empty Vue application using Vuex. The previous section described how that was done via the CLI, and if you followed along, you've got one ready to go. If not, go ahead and create one now, ensuring you enable Vuex. In this exercise, we'll simply set a few values in the state and display them in a component.

To access the code files...

Applying Getters

In the previous exercise, you saw how simple it was to directly access state, but there are times when you may need more complex views of your state. To make this easier, Vuex supports a feature called getters.

Getters have their own block within the store, and you can define as many as necessary. Each getter is passed the state as an argument, which lets you use whatever you need to create your value. Finally, the name of the getter is how it will be exposed. Consider this simple example:

state: {
  name: "Raymond",
  gender: "male",
  job: "Developer Evangelist"
},
getters: {
  bio(state) {
    return `My name is ${state.name}. I'm a ${state.job}`;
  } 
}

This store defines three state values (name, gender, and job), and also provides a "virtual" property named bio that returns a description of the data. Note that the getter only uses two of...

Getters with Parameters

While Getters can be accessed directly via $store.getters properties, you may run into situations where you need a bit more control over how the getter works. Parameters provide a way to customize how Getters works. Consider the following store:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    books:[
      {type:'nonfiction', title:'Truth about Cats', pages: 200},
      {type:'nonfiction', title:'Truth about Dogs', pages: 100},
      {type:'fiction', title:'The Cat Said Meow', pages: 400},
      {type:'fiction', title:'The Last Dog', pages: 600},
    ]
  },
  getters: {
    fiction(state...

Modifying State with Mutations

So far, you've seen how to read data from a Vuex store, both with direct access to state and by using getters. But to actually change the state of a store, Vuex supports the idea of mutations. Mutations are methods you define in your store that handle changing state. So, for example, instead of your component simply setting a new value in the state, your component will ask the store to perform a mutation, and the store handles that logic itself.

Here's a simple example:

state: {
  totalCats: 5,
  name:'Lindy'
},
mutations: {
  newCat(state) {
    state.totalCats++;
  },
  setName(state, name) {
   state.name = name;
  }
}

In the preceding snippet, the store has two values in its state, totalCats and name. Two mutations exist to allow you to change these values. All mutations are passed a state object that gives you direct access...

Using Actions for Asynchronous State Changes

Actions in Vuex are the primary way of handling asynchronous logic for your store. Mutations have to be synchronous, but actions can be asynchronous if they choose. The other difference is that actions get a context object that represents the store itself. This lets actions call mutations or work with the state directly. In general, most developers will call mutations from their actions.

This probably seems a bit confusing, but in general, think of actions as your asynchronous support for your store. It will make sense once we see an example or two.

Let's look at a sample action. The following snippet contains one mutation and an asynchronous action that will make use of the mutation:

  mutations: {
    setBooks(state, books) {
      state.books = books;
    }
  },
  actions: {
    loadBooks(context)...

Simplifying with mapState and mapGetters

As one of the last features we'll cover with Vuex, let's look at mapState and mapGetters. These are handy utilities that help map state values and getters into your component's computed property. As a practical matter, it makes your HTML templates simpler. So instead of {{ $store.state.firstName }}, you can simply use {{ firstName }}. Instead of using {{ $store.getters.name }}, you can just use {{ name }}.

Both mapState and mapGetters can either take an array of values to map or an object where each key represents the name you wish to use in your component and the value is the state value or getter in the Vuex store. They are both used with your Vue application's computed block.

In this first example, two state values and three getters are mapped by their name alone:

mapState(["age", "rank", "serialNumber"]);
mapGetters(["name", "fiction", "nonfiction"...

Simplifying with mapMutations and mapActions

The final features we'll cover are very similar to the previous one: mapMutations and mapActions. As you can probably guess, these two features work very similarly to mapState and mapGetters, in that they provide a shorthand way to connect your code to Vuex mutations and actions without writing boilerplate code.

They follow the exact same format in that you can specify a list of items to map or specify a list while also providing a different name, as in the following example:

mapMutations(["setBooks"]);
mapActions(["loadBooks"]);

These can be used in your Vue component's methods block:

methods:{
    ...mapMutations(["setBooks"]),
    ...mapActions(["loadBooks"])
}

This then allows your Vue code to call either setBooks or loadBooks without specifying the store object, or dispatch and commit.

Now, let's try to create a simple...

Summary

In this chapter, you have seen most of Vuex's features and should now have an idea of how to both read from and write to the store. You employed mutations for synchronous changes and actions for asynchronous modifications. You created getters to provide access to virtual values based on your state. You have also seen how components look when working with the store. They've got less logic and simply hand off that part to the store. In larger Vue applications, this will become even more important. Your components will handle the UI and UX, but let the store handle the data layer. Having the store as a single source of truth, then, relieves you of so much "grunt" work that you will come to greatly appreciate Vuex, even in smaller applications.

In the next chapter, you will learn about using remote data with Vuex stores. Working with remote APIs is a common need in modern web applications. Integrating these APIs in Vuex will make it easier for the rest...

lock icon The rest of the chapter is locked
You have been reading a chapter from
Front-End Development Projects with Vue.js
Published in: Nov 2020 Publisher: Packt ISBN-13: 9781838984823
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.
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}