Using Getters and Mutations in Vuex

Tutorial 2 of 5

Using Getters and Mutations in Vuex

1. Introduction

In this tutorial, we will explore how to use two important aspects of Vuex - getters and mutations. Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application.

By the end of this tutorial, you will learn how to use getters to access the state in Vuex and how to use mutations to modify the state.

Prerequisites
- Basic knowledge of JavaScript
- Understanding of Vue.js fundamentals
- Familiarity with ES6 syntax

2. Step-by-Step Guide

Getters: Vuex getters are similar to computed properties in Vue. They receive the state as their first argument and can help us access the values from the state.

Mutations: Vuex mutations are the only way to change state in Vuex store. They receive the state as their first argument and an optional payload as the second argument.

Best Practices: It is recommended to use constants for mutation types rather than hardcoding them as strings.

3. Code Examples

Example 1: Using Getters

Let's create a store.js file and define our state and a getter.

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 10
  },
  getters: {
    // Our getter
    count: state => state.count
  }
})

In the example above, we have a count state and a count getter. This getter simply returns the count from the state.

To use this getter in a component:

computed: {
  count() {
    return this.$store.getters.count
  }
}

Example 2: Using Mutations

Let's add a mutation to our store that increments our count:

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 10
  },
  getters: {
    count: state => state.count
  },
  mutations: {
    increment (state) {
      // mutate state
      state.count++
    }
  }
})

To call this mutation from a component:

methods: {
  incrementCount() {
    this.$store.commit('increment')
  }
}

4. Summary

In this tutorial, we learned how to use getters to access the state and how to use mutations to modify the state. We also learned about the best practice of using constants for mutation types.

For your next steps, try creating a Vuex store with more complex state and write getters and mutations for them.

Additional Resources
- Vuex Documentation
- Vue.js Guide

5. Practice Exercises

Exercise 1: Create a Vuex store with a todos state, a getter that returns all todos, and a mutation that adds a todo.

Exercise 2: Add a mutation that removes a todo and a getter that returns the count of todos.

Solutions: Solutions and explanations can be found in the GitHub repository. Continue practicing by adding more complex states and operations to your Vuex store.