How to use Vuex getters to compute derived state?

To use Vuex getters to compute derived state, follow these steps:

  1. Define getters in your Vuex store:
// store.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { todos: [ { id: 1, text: 'Learn Vuex', completed: false }, { id: 2, text: 'Build an app', completed: true }, ... ] }, getters: { completedTodos: state => { return state.todos.filter(todo => todo.completed) }, incompletedTodos: state => { return state.todos.filter(todo => !todo.completed) } } }) export default store
  1. Access the computed values in your Vue components:
<template> <div> <h2>Completed Todos</h2> <ul> <li v-for="todo in completedTodos" :key="todo.id"> {{ todo.text }} </li> </ul> <h2>Incompleted Todos</h2> <ul> <li v-for="todo in incompletedTodos" :key="todo.id"> {{ todo.text }} </li> </ul> </div> </template> <script> import { mapGetters } from 'vuex' export default { computed: { ...mapGetters([ 'completedTodos', 'incompletedTodos' ]) } } </script>

In this example, we have defined two getters - completedTodos and incompletedTodos - based on the state of todos in the store. We use these getters in the computed section of the Vue component to access the derived state. The computed properties automatically update when the underlying todos state changes.

By utilizing getters, you can easily compute and access derived state in your Vue components, simplifying the management of complex state dependencies.