Vuex official website: vuex.vuejs.org/zh/

A preface.

Both Vue and React need to manage state. For example, components need to share state. What is shared state? For example, a component that needs to use another component’s state, or a component that needs to change another component’s state, are shared states.

Without effective management of state, when, why, and how it changes can get out of control, making it difficult to track and test.

In software development, there are some general ideas, such as isolation of change, convention is better than configuration, isolation of change is to do a good job of abstraction, some easy to change to find common, isolated, do not affect the other code. Convention over configuration is a lot of things we don’t have to write a lot of configuration, such as a few of us agreed, in the view folder can only put the view, can’t put the filter, the filter must be on the filter folder, that this is a kind of contract, agreement, we don’t have to write a lot of configuration files, and we are looking for all the view, Just look in the View folder.

According to these ideas, the solution to state management is to extract the states that need to be shared between components, follow specific conventions, and manage them uniformly so that the changes of state can be predicted.

What is Vuex

Vuex is a state management tool for vue.js application development. It uses centralized storage to manage the state of all components of an application, and responds with rules to ensure that state changes in a predictable way.

1. What is state management?

Vuex’s website says that “state management mode “,” centralized storage management “, these words and “state management” are the same meaning. It’s managing state.

We typically have many components that may share state between them. So how do we define this state? It is definitely not appropriate to define it in a component; define it in the outermost layer.

In the case of the VUE ecosystem, there are multiple components that share state, which is usually represented by variables that are shared between multiple components. When the number of shared variables increases, we store them with an object, and that object is the object that stores the shared state. Typically, this object is placed in an instance at the top of the VUE. Various other components are available.

Vue is reactive programming. If one component changes state, can other components respond in real time? This is what Vuex does. Its main functions:

  1. Managed state: Because it keeps various states in one place, it is also called centralized storage management or centralized loading management
  2. Reactive: When one component changes state, other components can respond in real time

2. What state should be managed in Vuex in general?

Not all states need to be managed by Vuex. Only states shared between multiple interfaces need to be managed by Vuex. Such as:

  • User login status: user name, avatar, nickname, etc. Many pages may use the user’s basic information, such as these unified information, we can put in a unified place for management.
  • Token: the token used by the user to log in. Some interfaces must have tokens to access, so these interfaces need to share tokens
  • Merchandise collection, items in shopping cart, etc. We can add product search and purchase in any interface, and then we can put it into Vuex

In VUEX, you can not only share state, but also respond in real time.

3. Design idea of Vuex

Vuex maintains an object globally and uses the singleton design pattern. In this global object, all properties are reactive, and changes to any property cause the component that uses that property to update. In addition, the state can only be changed through the COMMIT mode, realizing the one-way data flow mode.

Vuex integrates with DevTools Extension, the official debugging tool of Vue, and provides advanced debugging functions such as zero-configuration time-travel debugging and status snapshot import and export.

How does Vuex manage state between multiple components?

2.1. Single-interface state management

All we’ve encountered before is state management in a single interface. The single-interface state management has three parts, as shown in the figure below:

Part 1: State Part 2: View Part 3: Action

How do the three parts work? Normally state is represented by a variable, defined in the data property of the component.

<script>
    export default {
        name: "calculate".data() {
          return {
            counter: 0
          };
      }
    }
</script>
Copy the code

The counter variable is then referenced directly in the page via syntactic sugar. The value of counter is displayed on the page. Finally, we can add actions to the page, such as click events, to change the state.

This is the flow of state management in a single page.

2.2. Multi-interface state management

For example, we have a calculate.vue component


      data() {
          return {
            counter: 0
          };
      },
      methods: {
          add() {
            this.counter ++
          },
          dev() {
            this.counter --
          }
      }
    }
</script>
Copy the code

Then introduce the calculate. Vue component in app.vue

<script>
import Calculate from './views/calculate'

export default {
  name: 'App'.components: {
    Calculate,
  }
}
</script>
Copy the code

At this point, if you want to use the variable counter defined in calculate.vue in app.vue, is that ok? Direct use of the Calculate and App components is bound to generate an error, but the relationship between the Calculate and App components is parent-child and can be implemented using parent-child variable passing.

What if it’s not a father-son relationship? How do you do that? We can use Vuex.

2.3. Use of Vuex

To use VuEX, you first need to install the VUEX component

npm install vuex –save

–save means runtime requirements

Now that the components are installed, let’s see how they work.

Step 1: Add the Vuex code folder

Create/SRC /store/index.js under the SRC directory. Vuex is usually stored in the Store folder. Then create a file index.js under store

Step 2: Define the vuex component in the index.js file.

Vuex is a plug-in, vuE-Router is a plug-in, and plug-ins are used in a similar way.

1: Introduce VUE and VUex

import Vue from 'vue';
import Vuex from 'vuex';
Copy the code

2: install vuex

 Vue.use(Vuex);
Copy the code

3: Create a VUex object

const store = new Vuex.Store({
    state: {},mutations: {},actions: {},getters: {},modules: {}})Copy the code

Five objects are defined in the Store, and these five objects are fixed. What is the meaning of each object? More on that later.

4: vuex derived

export default store;
Copy the code

5: Introduce vuex in main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/index';

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router,
  render: h= > h(App)
})
Copy the code

Consider the issue of multi-interface state management in 2.2. The Calculate component has a counter and you want to use it in the parent app.vue, so this counter is a common state and can be defined in vuex.

2.4 Vuex Implements multi-interface status management

Now let’s see how vuex can be implemented.

1. Define a variable counter in vuex’s state

// Create a vuex object
const store = new Vuex.Store({
  state: {
    counter:0}})Copy the code

2. Use $store.state.counter in calculate.vue to get the counter variable in vuex

<template>
  <div>
    <h2>{{$store.state.counter}}</h2>
  </div>
</template>
Copy the code

So now we have our counter variable. And it can be used directly in calculate.vue or app. vue, or any other component. As shown below:

The next step is to implement + and -. So how do we do that? We might think so

<template>
  <div>
    <h2>-------calculate.vue-------</h2>
    <h2>{{$store.state.counter}}</h2>
    <button v-on:click="$store.state.counter++">+</button>
    <button v-on:click="$store.state.counter--">-</button>
  </div>
</template>
Copy the code

Counter ++ or store.state.counter++ or store.state.counter++ or store.state.counter Although this can work, the Vuex website recommends that we do not use this method because we cannot track the state changes after this operation. What does that mean? That’s where vuex comes in.

2.5 Vuex design idea

Vuex is essentially the design idea of singleton pattern

  • The shared state is extracted and handed over to the butler for unified management
  • Each view is then accessed or modified according to the specified rules.
  • That’s the idea behind Vuex.

Good rules are important here. What are the established rules? Let’s take a look at an official picture from Vuex

There are five elements in this

  • Vue compontents

  • State

  • Mutations

  • Action

  • Devtools

What are these parts for?

1. Vue Components

The green part of the diagram is the Vue componens, which refer to the state variable and trigger operations that modify the value of the variable.

2. State:

The value of the variable can be directly rendered to the Vue component, but as agreed, the Vue component cannot directly modify the value of State

3. The Mutations and Devtools

If the Vue component wants to change the state in state, it cannot change state directly. Instead, it needs to perform COMMIT, which is submitted to Mutations, which triggers changes to the state. Why is that? This has something to do with Devtools.

We see a gray piece of Devtools, what is that? This is a browser plug-in developed by Vue. This plugin helps us record the state of each variable change in state. Why record the state?

For example, if we have multiple components changing a state in vuEX at the same time, and everyone changes it, who finally changes the value? If there’s no record of the state change, then we don’t know who did it. The Devtools tool provided by Vue can be used to record the status of each change.

However, if we modify the component directly, we don’t go through The Devtools process and Devtools can’t record it. If you change the value of a variable directly from state (red arrow), instead of going through the blue arrow, Devtools will not be able to record the state of the change without going through Devtools.

4. Action

Action is mainly used for asynchronous operations, while mutations are used for synchronous operations, so mutations that the VUE component wants to change a variable can be done directly, which can also be recorded using Devtools. But what about asynchrony? Devtools can only be used to record synchronous state, but not asynchronous state. So, there is an action. Action is used to handle asynchronous operations. When the action is finished, it will be handed over to Mutations, which is the simultaneous operation, and Devtools can also handle it.

When do asynchronous operations happen? BackEnd sends network requests. Therefore, the Action module points to BackEnd and sends network requests.

2.6 Using Devtools

1. Install Devtools

To install Devtools, open Google Chrome browser and click on the three dots in the upper right corner -> More Tools > Extensions -> Open the Chrome Web App Store -> Search For Devtools.

Find Devtools for VueJs –> Add it to Chrome as shown below:

Then install the plug-in.

2. Use Devtools to track status

After Devtools is installed in Chrome, you can open the console and see vue at the end of the menu bar.

The second button monitors variable state changes.

If we use $store.state.counter++, Devtools cannot monitor state changes, but if we use mutations, we can.

3. Change the value of counter from mutation

First, we want to implement + and – logic in the page, as shown below:

This logic is used in the calculate.vue component, as well as in the app. vue component, so we define it in the vuex plug-in. Increase () and Decrease (), and change the value of the variable counter

const store = new Vuex.Store({
  state: {
    counter: 100
  },
  mutations: {
    increase(state) {
      state.counter ++;
    },
    decrease(state){ state.counter --; }}})Copy the code

Increase () and decrease(), their built-in arguments are state.

How do you define it on the caller? That is, how do the two mutations methods defined in Vuex be used in calculate.vue and app. vue?

<template>
  <div>
    <h2>-------calculate.vue-------</h2>
    <h2>{{$store.state.counter}}</h2>
    <button v-on:click="add()">+</button>
    <button v-on:click="sub()">-</button>
  </div>
</template>

<script>
    export default {
        name: "calculate".data() {
          return{}; },methods: {
        add() {
          this.$store.commit("increase");
        },
        sub() {
          this.$store.commit("decrease")}}}</script>
Copy the code

On the caller, we’ll use this. code.store.mit () to commit the change.

Click + or – on the left, and devTools logs every state change on the right.

2.7 summarize

At the heart of Vuex’s app is the Store, which is basically a container that contains most of the states in your app. Vuex differs from a purely global object in two ways:

  1. Vuex’s state storage is reactive. When the Vue component reads the state from the Store, if the state in the store changes, the corresponding component is updated efficiently accordingly.

  2. You can’t just change the state in the store. The only way to change the state in a store is to commit mutation explicitly. This allows us to easily track each state change, which allows us to implement tools that help us better understand our application.

Core concepts of Vuex

Vuex has five core concepts

  • State
  • Getter
  • Mutations
  • Action
  • Modules

These concepts: State, Mutations, Action have been improved. Let’s focus on getters and Modules. Before we look at getters, let’s look at one concept: a single state tree

4.1 Single state tree

What is a single state tree?

For example, our personal information, social security information is stored in the social security system, provident fund information is stored in the provident fund system, medical insurance information is stored in the medical insurance system. This has both advantages and disadvantages. The advantages are that information is more secure and isolated from each other; The downside is that if you want all the information you have to go to a lot of places to get it.

The idea of a single state tree is to store all of your information in one store, and if you need some data, you just go to that store and get it. Do not define multiple stores in the system, which is difficult to manage and maintain.

Single state tree meaning: Build only one store in a project.

4.2 Using getters

A Getter is a little bit like compute for a property. When do you use computed properties? We usually use computed properties when we need to display the computed value of an attribute.

The same is true for getters: when a state property needs to be computed and displayed, we use the Getter property. So let’s say we want to square counter.

What do we do if we don’t use computed properties? Here’s what we say in the Calculate. vue component.

<h2>{{$store.state.counter * $store.state.counter}}</h2>
Copy the code

1. Compute square using the compute property

Then, if you’re going to do the same in app.vue, do another one. Observation: This code is long and not maintainable, so we can put it in the Getter. Return after unified calculation

const store = new Vuex.Store({
  state: {
    counter: 100
  },
  mutations: {
    increase(state) {
      state.counter ++;
    },
    decrease(state){ state.counter --; }},getters: {
    // The first argument in the getter is state
    powerCounter(state) {
      return state.counter * state.counter
    }
  }
})
Copy the code

We define a square method, powerCounter(), which takes state as its first argument, so we can just take the counter property and operate on it. What happens next in the caller?

 <h2>{{$store.getters.powerCounter}}</h2>
Copy the code

Through $store. Getters. PowerCounter calculation attributes.

2. Define the second parameter of the method in getters

What if we want to use another getters calculation in another method? The methods defined in getters also have the default second argument getters example: compute counter squared + 100 what can we do at this point? The powerAndAdd method is defined below, and its second parameter is getters by default.

getters: {
    // The first argument in the getter is state
    powerCounter(state) {
      return state.counter * state.counter
    },

    powerAndAdd(state, getters) {
      return getters.powerCounter + 100}}Copy the code

We have done the square operation in powerCounter, and now we can directly use this result to calculate. In the powerAndAdd method, the first argument is still state and the second argument is getters. We can get the first method powerCounter using getters and add +100 to the first method.

Call the powerAndAdd method in the calculate.vue component

<template>
  <div>
    <h2>-------calculate.vue-------</h2>
    <h2>{{$store.state.counter}}</h2>
    <button v-on:click="add()">+</button>
    <button v-on:click="sub()">-</button>
    <h2>Counter take square: {{$store. Getters. PowerCounter}}</h2>
    <h2>After square + 100: {{$store. Getters. PowerAndAdd}}</h2>
  </div>
</template>
Copy the code

The final effect is as follows:

3. Customize methods with parameters in getters

In the getter, the method defined in getters, the first argument is state and the second argument is getters. Both of these are default. What if I have a method that wants to pass custom parameters? Instead of adding directly after getters, you can use anonymous functions to accept custom parameters. Take the add method below

getters: {
   // The first argument in the getter is state
   powerCounter(state) {
     return state.counter * state.counter
   },

   powerAndAdd(state, getters) {
     return getters.powerCounter + 100
   },

   add(state, getters) {
     return (num1, num2) = > num1 + 100+ num2; }}Copy the code

When used, pass two parameters directly, as follows:

< h2 > accumulative +100: {{$store.getters.add(200.500)}}</h2>
Copy the code

4.3 Use of Mutations

1. The only way to change store state in Vuex is:Submit Mutations

  1. Mutations has two main parts
  • Part of it is the event type
  • The other part is the callback function (handler), whose first argument is state

Such as:

mutations: {
    increase(state) {
      state.counter ++;
    },
    decrease(state){ state.counter --; }}Copy the code

Increase is the event type and the method body is the callback function. The first argument to the callback function is state

Once the mutations method is defined, if we want to call it, we’ll call it as a COMMIT

add() {
  this.$store.commit("increase");
},
Copy the code

2.Mutations transfer parameters

So if I had a + and a -, what if I had a +5, a +10, a -100? We need to define a method to receive the parameter. How to define the parameter in Mutation and how to pass the parameter?

There are two ways of submitting data in Mutation

1. The first method of data transmission

Let’s look at the steps: Step 1: Define two buttons in the calculate.vue component, one +5 and one +10

    <button v-on:click="addCount(5)">+5</button>
    <button v-on:click="addCount(10)">+ 10</button>
Copy the code

I’m defining a method called addCount()

     methods: {
            add() {
              this.$store.commit("increase");
            },
            sub() {
              this.$store.commit("decrease")},addCount(num){}}Copy the code

Step 2: Define a mutation method in the store and accept an argument, increaseCount as follows

mutations: {
    increase(state) {
      state.counter ++;
    },
    decrease(state) {
      state.counter --;
    },
    increaseCount(state, num){ state.counter += num; }}Copy the code

The first argument to the increaseCount() method is state, and we can accept the variable with the second argument. This is not the same as getters, which write an anonymous function to accept custom variables. Step 3: Call the Store increaseCount method in the defined Calculate component

        addCount(num) {
          this.$store.commit("increaseCount", num)
        }
Copy the code

When passing the parameter, we place the custom parameter in the second variable position.

Step 4: Check the effect

1. The second way of data transmission

The first method of data passing is concrete parameters. The second method of data passing is objects. Let’s look at the second one

Here’s a comparison: The previous method used to pass parameters directly

        addCount(num) {
          this.$store.commit("increaseCount", num)
        },
Copy the code

How about using object pass parameters?

addCount(num) {
          this.$store.commit({
            type: "increaseCount".num: num
          })
        },
Copy the code

It should be noted that different writing methods have slightly different meanings.

  • Mode 1 is passed to mutation with the specific parameter values.
  • Method two is passed to mutation as an object.

Again, the method is defined in mutation and accepts a parameter obj

 increaseCount(state, obj) {
      console.log(obj);
  },
Copy the code

The first way is passed: You can see the content of the concrete parameters that are passed in

The second way is to pass an object

    increaseCount(state, obj) {
      console.log(obj);
      state.counter += obj.num;
    },
Copy the code

3. Response rule of Mutation

The state of Vuex’s store is responsive, and the Vue component updates automatically when the data in the state changes. However, the corresponding rules need to be adhered to

1) Add new attributes

For example, we modify the info name parameter. Let’s look at the effect

Step 1: Define the variable info in store/index.js state and define the method updateInfo to modify info

const store = new Vuex.Store({
  state: {
    info: {
      name: "Fifty".age: 58.sex: "Male"}},mutations: {
    updateInfo(state, name) {
      // Change the value of name in info
      state.info["name"] = name; }}})Copy the code

Step 2: Display the info content in calculate.vue and modify the info content

<template>
  <div>
    <h2>-------calculate.vue-------</h2>
    <h2>info: {{$store.state.info}}</h2>
    <button v-on:click="updateInfo">Modify the name</button>
  </div>
</template>

<script>
    export default {
      name: "calculate".methods: {
        updateInfo() {
          this.$store.commit("updateInfo"."Daisy")}}}</script>
Copy the code

The mutation method updateInfo() in store is called directly. In the updateInfo() method, the name value is reset using state.info[“name”]=name, and the effect is immediately visible on the page

However, not all assignments using state.info[“name”]=name are responsive, so let’s add a hobby to info to try the first step: Add mutation methods to store/index.js, add hobby, hobby properties that were not previously available in info

    updateInfoHobby(state, hobby) {
      state.info["hobby"] = hobby
      console.log(state.info)
    }
Copy the code

Step 2: Define methods to modify Hobby

        updateInfoHobby() {
          this.$store.commit("updateInfoHobby"."Basketball")}Copy the code

Step 3: Look at the results

We noticed that after clicking the button to add A Hobby, the page did not add a Hobby in response, but in the right console, we saw that the $store.info property did already have a Hobby.

This is the first condition for Mutation to modify the state attribute: the properties need to be initialized in the store in advance for a responsive display. What if some attributes are added dynamically and you don’t know in advance? We need to add it in a different way

updateInfoHobby(state, hobby) {
      Vue.set(state.info, "hobby", hobby);
    }
Copy the code

Take a look at the results:

Another way to do this is to assign a value to the original object using the entire new object.

Conclusion:

  1. Initialize the required properties in store ahead of time
  2. When adding new attributes to objects in state, use the following method

Set (obj, newProp, value). Set (obj, newProp, value)

2) Delete attributes

Vue. Delete (obj, prop) can also be used when deleting attributes

4. Type constants of Mutation

In mutation, we defined many event types (i.e., method names). As our project grew larger, vuEX managed more and more states, requiring more and more state updates, which meant more and more methods were in mutation. If there are many methods, the name is prone to error, so we extracted the constants in Mutation. Define it in a public file. Here’s how to do it: Take modifying the counter method. Let’s extract the increment method increase.

Step 1: Add a new mutation-types.js file and define a constant INCREASW

export const INCREASW = "increase"
Copy the code

Step 2. Define method names using constants in store mutation

/ / the introduction of mutation
import { INCREASW} from './mutation-types'

const store = new Vuex.Store({
 mutations: { [INCREASW](state) { state.counter ++; }}})Copy the code

Here we use [] to define the method name, which is passed in as a variable.

Step 3: Introduce mutation-types in calculate.vue and commit to mutation using commit

 import {INCREASW} from '.. /store/mutation-types'
        add() {
          this.$store.commit(INCREASW);
        },
Copy the code

That’s how you extract the variable. When we need to change the variable name, we don’t change it everywhere, just the value of the variable name in mutation-types.

5 Mutation synchronization function

In general, Vuex requires that the methods in our Mutation be synchronous methods. Why is that? The main reason was that devTools did a good job capturing the mutation snapshot when we used devTools. But if the operation is asynchronous, DevTools will not do a good job of tracking when the operation was completed.

For example, we will asynchronously handle the [modify name] action. In setTimeout,

   updateInfo(state, name) {
      setTimeout(function(){
        state.info["name"] = name;
      }, 1000)}Copy the code

Then click the [Modify Name] button, you will find that the name of Wang Wu is changed to Zhao Liu, and the page is changed, but it is not changed in devTools, as shown below:

In Mutation, do not perform asynchronous operations. Devtools may not be able to track if an asynchronous operation is performed. If you do have an asynchronous operation, use action. action functions like Mutation, but it mainly handles asynchronous operations. Let’s look at Action in Action

4.4 Use of Action

As mentioned above, the use of action is similar to that of Mutation. But actions primarily deal with asynchronous operations. How to replace asynchronous operations written in the updateInfo method with actions?

Methods defined in mutation

    updateInfo(state, name) {
      setTimeout(function() {
        state.info["name"] = name;
      }, 1000)}Copy the code

Methods defined in action

actions:{
    aUpdateInfo(context) {
      setTimeout(function () {
        context.commit("updateInfo")},1000)}},mutations: {
    updateInfo(state, name) {
      state.info["name"] = name; }}Copy the code

We define a method aUpdate corresponding to updateInfo. The entry is context, notice that it’s not state, it’s the entire store. The asynchronous operation is defined in the aUpdate method and then calls the method in Mutation. Note: this is an official requirement, so the action should not modify the state itself, so the modification of the state is carried out in Mutation.

Next, on the button [change name], redefine the click event, this time not pointing directly to mutation, but to the action. * method that called mutation using: this.store.com MIT (…) ∗ calls action methods using this.store.com MIT (…) * Call action method using: this.store.com MIT (…) ∗ calls action methods using this.store.dispatch(…)

    updateInfo() {
      / / called mutation
      Use new code.store.com ("updateInfo", "new code.store.com ")
      / / calls to action
      this.$store.dispatch("aUpdateInfo"."Daisy")},Copy the code

The effect is shown below:

You can see that DevTools recognizes the info change

4.5 Module Usage

Module means Module, why did we introduce modules in Vue?

  1. Vue uses a single state tree, which means that a lot of state is managed by VUEX
  2. As apps get complicated, the store gets bloated,

To solve this problem, Vuex allows us to split the Store into modules. Each module has its own states, Mutations, Actions, getters, and so on

It is written as follows:

const store = new Vuex.Store({
  modules: {a: {state: {},getters:{

      },
      mutations:{

      },
      actions: {}},b: {}}})Copy the code

As mentioned above, a module is defined in store, which has two modules A and B. Module A defines a set of getters, States, mutations, and actions, as can module B

So how do you use it after you define it? Let’s do it one by one

1. The state calls

Define a moudules in the Store /index.js file, and then define state

const module1 = {
  state: {
    message: "This is the state defined in Module1."}},const store = new Vuex.Store({
  modules: {module1: module1
  }
}
Copy the code

As shown above, how do YOU call Message in Module1?

    <h2> message : {{$store.state.module1.message}} </h2>
Copy the code

2. The getter call

Add getters to Module1

const module1 = {
  state: {
    message: "This is the state defined in Module2."
  },
  getters: {extraMessage: function(state){
      return state.message + "aaaa"; }}}Copy the code

The attributes defined in Getters, described earlier, are equivalent to computed attributes. What about calling the computed properties in getters?

<h2> extraMessage: {{$store.getters.extraMessage}}</h2>
Copy the code

When called, it is a little different from state. There is no need to specify the modules module name. First, we go to getters defined in Store to search for them. If they cannot be copied, we will search for them in Modules1 module. Therefore, we try not to have the same name when defining them

3. Mutation calls

We define a button to update the value of message

const module1 = {
  state: {
    message: "This is the state defined in Module2."
  },
  getters: {extraMessage: function(state){
      return state.message + "aaaa"; }},mutations: {changeMessage: function(state) {
      state.message = "Replace with a new message"}},actions: {}}Copy the code

Next, the caller defines a button that replaces the value of message. Then changeMessage

<button v-on:click="changeMessage"> replace message < / button >Copy the code
        changeMessage() {
          this.$store.commit("changeMessage")}Copy the code

We can see that when calling the mutation method, we use commit. This is the same as calling store mutation. You can also pass parameters in the same way as in store

4. Call action

Where we modify the message message, we set it to asynchronous modification as follows:

const module1 = {
  state: {
    message: "This is the state defined in Module2."
  },
  getters: {extraMessage: function(state){
      return state.message + "aaaa"; }},mutations: {changeMessage: function(state) {
      state.message = "Replace with a new message" + ", bbbb"; }},actions: {
    aChangeMessage: function(context) {
      setTimeout(() = > {
        context.commit("changeMessage")},1000)}}}Copy the code

Add a setTimeout to actions, which is asynchronous. The caller needs to use the dispatch method to point to actions when calling

        changeMessage() {
          this.$store.dispatch("aChangeMessage")}Copy the code

So that’s the use of the methods that define States, getters, mutations, actions in Modules

This completes the use of Vuex.