Why write this article? Many new users are ignorant of vuex and don’t know how it works. On the one hand, I want to lead you to use VUEX from the simplest and most basic place. On the other hand, I also want to review VUEX for myself. Ok, no more nonsense, come with me to learn vuex.

Vuex has five core concepts that you need to understand. Mutations 4. mutations 4. actions 5. modularization management modules

1. What is VUex?

Before we learn to use it, we need to know what vuex is. So what is vuex? Before we learn something new, the first thing we should consider is to go to its website. Yes, the answers there may not be the best to understand, but they are certainly the most complete.

In simple terms, it is a state manager. In daily development, we often encounter the following two problems:

  • Multiple views depend on the same state.
  • Actions from different views need to change the same state

For problem one, the method of passing parameters can be cumbersome for multi-layer nested components and does nothing to transfer state between sibling components. For problem two, we often use parent-child components to reference directly or to change and synchronize multiple copies of state through events. These patterns are very fragile and often result in unmaintainable code.

So why don’t we extract the shared state of the components and manage it in a global singleton? In this mode, our tree of components forms a giant “view” where any component can get state or trigger behavior no matter where it is in the tree!

By defining and isolating concepts in state management and by enforcing rules to maintain independence between views and states, our code becomes more structured and maintainable.

This is The basic idea behind Vuex, which borrows from Flux (a Labour of New Window), Redux (a Labour of New Window) and The Elm Architecture (a Labour of New Window). Unlike other patterns, Vuex is a state management library designed specifically for vue.js to leverage the fine-grained data response mechanism of vue.js for efficient state updates.

2. When should I use Vuex?

Vuex helps us manage shared state and comes with more concepts and frameworks. This requires a trade-off between short-term and long-term benefits. Using Vuex can be tedious and redundant if you don’t plan to develop large, single-page applications. That’s true — if your application is simple, you’d better not use Vuex. Use parent-child communication or $bus. However, if you need to build a medium to large single-page application, and you’re probably thinking about how to better manage state outside of components, Vuex would be a natural choice.

3. Install Vuex and use the simplest store?

When you build the scaffolding, you can choose to install it directly, at which point VUX will automatically download the dependency packages for you and build the related files. But if you don’t, you’ll need to download the dependencies yourself, create a store folder under SRC, which is the same as the router folder, and import the registration in main.js.

At the heart of every Vuex application is the Store. A “store” 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.

First, the original state

1.1. Define native state in the repository

1.2. Direct access on the page (not recommended)

This method is not recommended, but it does not mean that it cannot be used, and VUEX recommends that we use it in computed.

1.3 use method access

1.4. Use mapState auxiliary function for access

Official answer: When a component needs to fetch multiple states, it can be repetitive and redundant to declare all those states as computed properties. To solve this problem, we can use the mapState helper function to help us generate calculated properties that will save you from pressing the key:

The code above shows that you can simplify it by using the mapState helper function, and you can alias it and use a nickname. (Alias is object, not array)

Modifier getters

Sometimes we need to derive some state from the state in the store, such as reversing the list: This is not wrong, but think about it. If multiple components have to use the reversed data, do you have to process it again after each component has obtained the value? This is not ideal. Vuex allows us to define “getters” (you can think of them as computed properties of the store) in the store. Just like evaluating properties, the return value of a getter is cached based on its dependency and is recalculated only if its dependency value changes. The Getter accepts state as its first argument

2.1. Define the getters method in the repository

2.2 Use method access

2.3 use mapGetters auxiliary function for access

If you think it’s a bit silly to use method access directly, getters also has a helper function like Status, which also supports a small name. (Alias is object, not array)

Third, modify the status of mutations

// this.$store.state.XXX = XXX;

The only way to change the state in Vuex’s store is to commit mutation. Mutations in Vuex are very similar to events: each mutation has a string event type (type) and a callback function (handler). This callback is where we actually make the state change, and it takes state as the first argument:

3.1 Define Mutation in the warehouse

3.2 Commit Mutation in the componentstore.commitMethod trigger)

You cannot call a mutation handler directly. This option is more like event registration: “This function is called when a mutation of type ADD is triggered.” To wake up a mutation handler, you need to call the store.mit method with the corresponding type.

3.3 Submit using the auxiliary function mapMutations (Support renaming change)

3.4 Using object-Style Submission (official recommendation)

  • You can name an object as you like, but you can call it payload.
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
Copy the code

The Mutation complies with the Vue response rules

Since the state in Vuex’s Store is responsive, the Vue component that monitors the state updates automatically when we change the state. This also means that mutation in Vuex requires the same precautions as mutation in Vue:

  1. It is best to initialize all required properties in your store in advance.
  2. When you need to add new properties to an object, you should
  • Use vue.set (obj, ‘newProp’, 123), or

  • Replace an old object with a new one. For example, using the object expansion operator, we can write:

    state.obj = { ... state.obj, newProp: 123 }Copy the code

    An important rule to remember is that mutation must be a synchronization function

Async Actions

Mixing asynchronous calls in mutation can make your program difficult to debug. For example, when you call two mutations containing asynchronous callbacks to change the state, how do you know when to call back and which to call first? That’s why we have to distinguish between these two concepts. In Vuex, mutation is a synchronous transaction: the Action is similar to mutation, except that:

  • The Action commits mutation rather than a direct state change.
  • Actions can contain any asynchronous operation.

4.1. Let’s register a simple action:

The Action function accepts a context object with the same methods and properties as the store instance, so you can submit a mutation by calling context.mit. Or get state and getters via context.state and context.getters. When we cover Modules later, you’ll see why the context object is not the Store instance itself.

In practice, we’ll often use ES2015’s parameter deconstruction to simplify code (especially if we need to call COMMIT many times).

Assign actions to components (actions triggered by the store.dispatch method)

4.3 Use mapActions helper functions to distribute actions (rename supported)

4.4 Using Object-Style Submission (official recommendation)

actions: {
  incrementAsync ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}
Copy the code

Fifth, modular management modules

With a single state tree, all the states of an application are grouped into one large object. When the application becomes very complex, the Store object can become quite bloated.

To solve these problems, Vuex allows us to split the Store into modules. Each module has its own state, mutation, action, getter, and even nested submodules — split the same way from top to bottom

Then register the module in index:

Corresponding to the above four core concepts of the use of the method must be added to the use of the module.

Previous good articles of the author:

Learn how to use XSS attack to experience a hacker

8 ways for components to communicate, have you figured it out?

Learn Node.js from 0 to 1: Getting your first taste of the API