Vuex core concepts – actions and getters

Article directory

  • actions and getters
    • 1. Function of actions
          • purpose of usage:
    • 2. Use of actions
          • Execution principle
          • Code example:
    • 3. Auxiliary function mapActions in actions
          • Code example:
    • 4. Core-getters
          • 1. What are getters?
          • 2. The role of getters:
          • 3. Two ways to access getters:
          • 4. Use of getters:
          • 5. Summary:

actions and getters

The following is a description of the basic use of actions

1. The role of actions

Actions in Vuex are functions used to handle asynchronous operations and submit mutations.
Its function is to perform asynchronous operations in the application, such as sending network requests, obtaining data, etc., and trigger mutations to change the state based on the results of the operations.

Purpose of use:

The main purpose of using actions is to separate asynchronous logic from components and make the code more efficient.
Plus modularity and maintainability. It can help us manage complex asynchronous operation processes and maintain state consistency.

2. Use of actions

In Vuex, we need to first define an object containing various action functions, and trigger specific actions through the dispatch method. Each action function can accept a context object as a parameter, which contains methods and properties in the store instance. Mutations can be submitted through the context.commit method, and the state can also be accessed through context.state.

Execution Principle

Code example:

Step 1: Define actions processing function

 // 3. Actions handle asynchronously
  // Note that State cannot be operated directly. To operate State, commit mutations are also required.
  actions: {<!-- -->
    // context context (not divided into modules here, can be used as a store warehouse)
    // context.commit('mutations name', additional parameters)
    changeCountAction (context, num) {<!-- -->
      // Here is setTimeout to simulate asynchronous, most of the time will be sending requests in the future
      setTimeout(() => {<!-- -->
      //addCount is in the mutations method
        context.commit('addCount', num)
      }, 1000)
    }
  }

Step 2: Use actions in the component

<button @click="changeCount">Change 1 second to 666</button>

//Trigger event and call method
    changeCount () {<!-- -->
      // Call actions → dispatch (method name in actions configuration object, additional parameters)
      this.$store.dispatch('changeCountAction', 666)
    }

  • It should be noted that actions can handle the results of asynchronous operations by returning a Promise, so that we can use async/await syntax in components to handle asynchronous processes.

3. Auxiliary function mapActions in actions

mapActions extracts the methods in actions and maps them to component methods.

  • Specifically, the mapActions function accepts an array or object containing the action name and returns an object containing the corresponding action method. In this way, these mapped methods can be used directly in the component without manually calling this.$store.dispatch to trigger actions.
Code example:
//Introduce the mapActions function into the component
import {<!-- --> mapActions } from 'vuex';

// Use the mapActions function in the component to map actions
export default {<!-- -->
  methods: {<!-- -->
    ...mapActions(['fetchData', 'submitData']),
    // Or use object form for mapping
    ...mapActions({<!-- -->
      fetchData: 'fetchData',
      submitData: 'submitData'
    })
  }
}

In the above example, we first import the mapActions function from the vuex module. Then, the … expansion operator is used in the component’s methods option to add the mapped action method to the component’s method.

Now, we can directly call the fetchData and submitData methods elsewhere in the component without having to manually use this.$store.dispatch to trigger the execution of actions. For example:

//Call the mapped action method
this.fetchData();
this.submitData();

It should be noted that the mapped action method is still within the scope of the component, so you can access other properties and methods of the component through the this keyword just like ordinary component methods.

By using the mapActions function, we can use actions in components more conveniently, and improve the readability and maintainability of the code.

4. Core-getters

1. What are getters?

In Vuex,getters are a core concept for deriving state. It is similar to a computed property in a component, allowing us to derive new state from the state in the store and use it as responsive data for the component.

2. The role of getters:

The main function of getters is to wrap and process the state in the store to provide higher-level data access and operations. By defining getters, we can avoid repeatedly writing the same logic in multiple components, while achieving data encapsulation, reuse, and independence.

3. Two ways to access getters:

① Access getters through store (native method)
{{ $store.getters.method name}}

② Mapping through the auxiliary function mapGetters

computed: {<!-- -->
...mapGetters(['filterList'])
]
4. Use of getters:
 Note:
 1. The first parameter of the formal parameter is state
 2. There must be a return value, which is the value of getters

In vuex: provide data and function methods

const store = new Vuex.Store({<!-- -->
  // Turn on strict mode (needs to be turned off when online)
  strict: true,


  // 1. Warehouse data (data shared by all components) can be provided through state
  state: {<!-- -->
    title: 'Warehouse title',
    count: 100,
    list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  },

//Use getters
  getters: {<!-- -->
    // be careful:
    // 1. The first parameter of the formal parameter is state
    // 2. There must be a return value, and the return value is the value of getters
    filterList (state) {<!-- -->
      return state.list.filter(item => item > 5)
    }
  }

In the component: use

 <!-- Native direct access -->
    <div>{<!-- -->{<!-- --> $store.getters.filterList }}</div>

//Import the auxiliary function first
import {<!-- --> mapState, mapMutations, mapActions, mapGetters } from 'vuex'

  computed: {<!-- -->
    // 1. mapState and mapGetters are mapping properties
    //state helper function
    ...mapState(['count']),
    ...mapGetters(['filterList'])
  },


<div>{<!-- -->{<!-- --> filterList }}</div>
5. Summary:

It should be noted that because getters are reactive, they will be automatically updated when the related state changes. This means that when using getters in a component, when the dependent state changes, the corresponding getters will also be recalculated.

To summarize, getters are the core concept in Vuex for deriving state and providing data manipulation. It makes it easier for us to obtain and process the state in the store, and provides a reusable and responsive data access method.

syntaxbug.com © 2021 All Rights Reserved.