Vue.js / Vue State Management (Vuex & Pinia)

Using Getters and Mutations in Vuex

In this tutorial, we'll dive into two key aspects of Vuex - getters and mutations. We'll learn how to leverage getters to access the state and mutations to modify it.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores state management using Vuex and Pinia.

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.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help