State, mutation, action, getter and module of vuex


Describe the use and relationship of state, mutation, action, getter and module of vuex,
Give examples to illustrate how they are used.

1. Store data state global data as long as it is changed, all the places used will change
2. Change data (synchronous) mutation change state by submitting commit
3. Change data (asynchronous) action can not be changed directly, it needs to be changed through mutation
4. The change of the state of the calculation property of the getter is only used, and does not affect the global situation
5. The template data module contains a complete set of state, mutation, action and getter,
There can be multiple modules, and the state, mutation, action and getter of each module are independent

Because the mutation can only be synchronous operations, but in actual projects, there will be asynchronous operations; then action is set for asynchronous operations. In this way, it turns out to submit mutation in action and then submit action in methods of component; only dispatch function is used when submitting action, while commit function is used for mutation.

 Five parts are not necessary. You can add whatever you need.
 However, vuex, no matter how simple it is, will at least be composed of state and mutation

//Call to get change data
/ / wx/getAppid calls the specified method from vuex.
//In vuex, dispatch is needed to trigger methods in actions
store.dispatch(“wx/getAppid”, { domain: window.location.href }).then((res)=>{

//Presentation data

{{ wx.appid }}

// import { mapState } from “vuex”
// computed: {
// …mapState({
// wx: (state) => state.wx
// })
// }

//Warehouse stores change data
import { getAppid } from “@/api/index”;
//Store state global variables
const state = {
appid: “”,

//The calculated property of state gets the state value through the method in the getter
// this.$store.getter.getappid
const getter ={
Return “appid is:+ state.appid
//Change the logic of state in state and synchronize operation
const mutations = {
SET_APPID: (state, appid) => {
state.appid = appid;

//Submit mutation, asynchronous operation
const actions = {
getAppid({ commit }, data) {
return new Promise((resolve, reject) => {
.then((res) => {
//Modify the commit in data actions to trigger the method in mutations
//The value of state can only be modified through mutations
//Pass the result to the place where the call is made, otherwise the called then has no output
.catch((err) => {
console.log (the “failure”);

// Module
//Module is to split the store into modules for easy management.
//Multiple modules can exist in a project
//Each module has a set of exclusive state getters mutation actions
// const module = {
// state: {},
// getters: {},
// mutations: {},
// actions: {}
// }

This work adoptsCC agreementThe author and the link to this article must be indicated in the reprint