Computer scienceFrontendVue.jsVuex

Getters in Vuex

6 minutes read

In Vue.js, state management in large applications can sometimes become complicated. To address this, Vuex, a state management pattern and library for Vue.js applications, provides a structured way to interact with an application's state. Among the features of Vuex are getters, which play a crucial role in managing and computing derived state. This topic will provide a detailed understanding of getters in Vuex, their role, and how to create and access them in Vue 3 components.

Understanding getters

Getters in Vuex are akin to computed properties for the store. They receive the state as their first argument. If there are other getters, they can receive them as the second argument. The primary role of getters is to compute derived state based on store state. This allows the developer to perform complex computations and data transformations. When the state changes, the computed state is cached and only recomputed when its dependencies change, making getters efficient. Essentially, getters are a way to get data from the Vuex store and use them in your components.

Creating getters in vuex

Defining getters in a Vuex store is a simple process. Here's how you can create a simple counter component that displays the doubled count using a getter from the store.js component:

// store.js
import { createStore } from 'vuex';

export const store = createStore({
  state: {
    count: 2
  },
  getters: {
    doubleCount: (state) => {
      return state.count * 2;
    }
  }
});

In this example, doubleCount is a getter that computes a new state, doubleCount, which is twice the count state. This means that when you need to use this derived state in your components, you can simply call this getter instead of duplicating this logic in multiple places.

Accessing getters in vue 3 components

With the advent of Vue 3's Composition API, accessing getters in components has become more intuitive. You can use the useStore hook to access the Vuex store and the computed function to create a reactive reference to the getter. Let's create Vue component Counter.vue:

<template>
  <article>
    <h1>Counter</h1>
    <p>Count: {{ count }}</p>
    <p>Doubled Count: {{ doubleCount }}</p>
  </article>
</template>

<script setup>
import { computed } from 'vue';
import { useStore } from 'vuex';

const store = useStore();
const count = computed(() => store.state.count);
const doubleCount = computed(() => store.getters.doubleCount);
</script>

In this example, doubleCount is a computed property that is reactively bound to the doubleCount getter in the store. This means that when doubleCount changes in the store, the component will reactively update to reflect the changes. This reactive binding is a robust feature of Vue 3 and Vuex, making your components more responsive to state changes.

Parameterized getters

Sometimes, you may need to pass dynamic values or parameters to a getter function to customize the data retrieval process. This is where parameterized getters come into play. In Vuex, you can define parameterized getters by returning a function from the getter. This returned function can then accept parameters, allowing you to customize the data retrieval based on those parameters.

getters: {
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  } 
}

In this example, getTodoById is a parameterized getter. It returns a function that takes an id parameter and returns the todo object from the state with a matching id.

To use a parameterized getter, you call it as a function with the required parameter(s) when accessing it from the store. Let us define the store with the getters to illustrate a product catalog where users can select a product by its ID to view its details. This is a common scenario in e-commerce applications.

// store.js
import { createStore } from 'vuex';

export const store = createStore({
  state: {
    products: [
      { id: 1, name: 'Smartphone', price: 699.99 },
      { id: 2, name: 'Laptop', price: 1299.99 },
      { id: 3, name: 'Tablet', price: 499.99 }
    ],
  },
  getters: {
    getProductById: (state) => (id) => {
      return state.products.find(product => product.id === id);
    },
  },
});

In this store:

  • You have a state with an array of products.

  • You define getProductById getter, which filters the products array to return only the product that has been selected via the its id.

<template>
  <article>
    <h1>Product Details</h1>
    <label for="product-select">Choose a product:</label>
    <select id="product-select" v-model="selectedProductId">
      <option v-for="product in products" :key="product.id" :value="product.id">
        {{ product.name }}
      </option>
    </select>
    <div v-if="productDetails">
      <p>Product ID: {{ productDetails.id }}</p>
      <p>Name: {{ productDetails.name }}</p>
      <p>Price: ${{ productDetails.price.toFixed(2) }}</p>
    </div>
  </article>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useStore } from 'vuex';

const store = useStore();
const products = store.state.products;
const selectedProductId = ref(products[0].id); // Initialize with the first product's ID
const productDetails = computed(() => store.getters.getProductById(selectedProductId.value));
</script>

In this component:

  • You use a <select> element with a <label> for accessibility, allowing users to choose a product by its name.

  • The v-model directive on the <select> element binds the selected value to selectedProductId.

  • The productDetails computed property dynamically fetches the details of the selected product using the getProductById getter with the current selectedProductId.

This example demonstrates how parameterized getters can be used in a Vuex store to retrieve and display details of a selected item, which is a common pattern in e-commerce websites and applications.

Getters illustration

By using parameterized getters, you can create more flexible and reusable getter functions in Vuex, enabling you to customize data retrieval based on dynamic parameters. This concept is particularly useful when dealing with data that requires dynamic filtering or querying.

Conclusion

Getters in Vuex provide a powerful and efficient way to manage derived state in Vue.js applications. They allow you to abstract complex computations and data transformations, keeping your components clean and focused on presentation logic. By understanding and effectively using getters, you can create more maintainable and performant Vue.js applications.

How did you like the theory?
Report a typo