The first word

The last lecture, “What the Hell is Vuex?”, was a perfect illustration of Vuex’s awesome skills. If compared Vuex to the inside of the pesticide liu bei, as you now know that the liu bei, he is a hero will let strength, and he played gun or double discharge, realize this, then the next step is to understand how he really wanted, is his left hand, right hand or to play, or both hands together with the gun?

Similarly, we already know that Vuex acts as a global administrator to help us unify the shared data of the project. How does Vuex manage it? How should we communicate with this administrator to effectively access and manipulate this shared data?

Say a

Vuex’s gut consists of five parts: State, Getter, Mutation, Action, and Module. I’ll elaborate on these five sections in several chapters, but I’ll start by going through State and getters with you.

Of course, in practice, these five sections are not necessary; you can add whatever you need. However, no matter how simple a Vuex is, it is usually made up of at least State and Mutation, otherwise you should consider whether Vuex is necessary at all.

Finally, note that the document sample code uses ES2015 syntax, if you haven’t seen it already, poke around here.

Single state tree

Vuex uses a “single-state tree”, which may be a bit confusing according to the official description, but let’s take a look at what a “single-state tree” is. Let’s take a look at what we mean by a tree here.

As shown in the figure above, the organizational structure of a company actually belongs to a tree structure. The general manager is the trunk of the tree, and other departments or professions all belong to branches of the tree.

Generally, a company will only have such a tree structure, if there are two equal general managers, then the company is likely to conflict in management, who will listen to the following people, right?

Ok, now let’s take a look at the official “single state tree” :

A single object (trunk) contains all (branches) of the application level state. 2. Each application (company) will contain only one Store instance object (trunk).

A single state tree allows us to directly locate any particular state fragment and easily take a snapshot of the entire current application state during debugging.

State

Let’s go back to the simple Store example code:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count: 0
  }
})Copy the code

So how do we present state in Vue components? Since Vuex’s state store is reactive, the easiest way to read state from a Store instance is to return some state in a calculated property, as follows:

// Create a Counter component const Counter = {data() {return {}}, template: '<div>{{count}}</div>', computed: { count () { return store.state.count } } }Copy the code

Every time store.state.count changes, the calculated properties are reevaluated and the interface is refreshed.

It is important to note that if you put store.state.count in data, the change in store.state.count does not automatically trigger the refresh of the interface.

{{store.state.count}}

, because there is no direct access to the store object in the template.

This mode relies on the global administrator store. If there are too many modules, it means that every module or page that uses the data in this state has to import the store, which is a bit uncomfortable. Of course, this maddening operation is officially frowned upon:

Vuex, via the Store option, provides a mechanism to “inject” state from the root component into each child component (by calling vue.use (Vuex)) :

Const app = new Vue({el: '#app', // Provide the store object to the "store" option, // this can inject the store instance into all the child stores, // child components: { Counter }, template: ` <div class="app"> <counter></counter> </div> ` })Copy the code

By registering the Store option in the root instance, the store instance is injected into all the children of the root component, which can be accessed through this.$store. Let’s update the implementation of Counter:

const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}Copy the code

The Vuex state is useful, but don’t abuse it:

Using Vuex does not mean that you need to put all the states into Vuex. While putting all the state in Vuex makes state changes more explicit and easier to debug, it also makes the code tedious and unintuitive. If there are states that belong strictly to a single component, it is best to treat them as local states of the component. You should make trade-offs and decisions based on your application development needs.

Getter

Sometimes, we will find that the data in State is not what we want directly, but needs to be processed accordingly to meet our needs.

For example, in a component, we need to convert the date in state to the day of the week to display:

computed: { weekDate () { return moment(this.$store.state.date).format('dddd'); }}Copy the code

Note: Moment is a third-party date-handling library that needs to be imported before you can use it.

This is fine if only one component needs to do this, but if this transformation is required in many components, then this function needs to be copied in each component. Moreover, if the product manager is in a bad mood and does not want to use the day of the week to display the date directly, then you have to change the date formatting method in all the components that use it, which is not very uncomfortable. Even if you isolate it as a common function, the various imports are cumbersome and, most importantly, difficult to manage uniformly.

So, at this point, Vuex introduced a really cool thing called the Getter. We can think of it as a computed property 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.

Let’s take a look at these two examples, focusing on the comments below:

Const store = new vuex. store ({state: {date: new date ()}, getters: {// Getter accepts state as its first parameter weekDate: state => { return moment(state.date).format('dddd'); }}}) getters: {dateLength: (state, getters) => {return getters.weekdate.length; }}Copy the code

Getters also expose store.getters, which you can access as properties:

console.log(store.getters.weekDate)Copy the code

We can easily use it in any component:

computed: {
  weekDate () {
    return this.$store.getters.weekDate
  }
}Copy the code

The format of weekDate display is different for each module. Some display all dates, while others need to display the day of the week.

Okay, so just pass it to the Getter, but how?

Because getters are cached as part of Vue’s responsive system when accessed via properties, you can’t directly store. Getters. WeekDate (‘MM Do YY’) because weekDate is not a function, it’s just a property.

So what if attributes can’t be passed in? So let’s just figure out how to turn this property into a function.

WeekDate: (state) => (FM) => {return moment(state.date).format(FM? fm : 'dddd'); }}Copy the code

Use as follows:

store.getters.weekDate('MM Do YY')Copy the code

Write in the last

Those who read the official documentation may wonder why helper functions such as mapState and mapGetters are not explained. Don’t worry, there will be a special chapter to explain it later, because I found that these auxiliary functions (including mapMutations and mapActions) are all created to solve the same problem, but in different forms, so it would be better to talk about them separately.

For the official I personally feel that write more easy to understand the place, directly quoted in. If you have any questions or questions about my understanding, please leave a comment.

Of course, this technical article in different stages of the people, there will be different experience. I know, there will be some shortcomings, I will continue to improve slowly. If the article is helpful to you, welcome to like and reprint, thank you!

Reprint statement:

Author: Ohiro said

The original link: www.jianshu.com/p/120eaf503…

Afterword.

The above is brother Hu to share the content today, like partners remember to like, collect ah, pay attention to Brother Hu has words, learning front end don’t get lost, welcome a lot of messages exchange…

Brother Hu has words, a technology, feelings of brother Hu! The current jingdong front – end siege lion. Hu Ge has words, focus on the field of front-end technology, share front-end system architecture, framework implementation principle, the latest and most efficient technology practice!