The first three chapters have updated the basic Vue usage and the basic Vue Router usage. If you have read the first three articles and are familiar with them, you can now develop simple applications such as blogs and e-commerce sites…….. The only problem is that as your business needs continue to increase, the volume of state data in your pages becomes extremely difficult to maintain. Vue provides a solution for state management. Vuex is similar to React Redux in that the data and logic in your pages are managed by store. The advantage is that the maintenance is easy and the individual component code is much cleaner.

This concludes the Vue series of articles and concludes the Vue family bucket. If you read along with the previous articles, you can now write a project to experience the magic of Vue. Vue can be used proficiently, the next step you should advance to a higher level, that is to study Vue source code. It’s only fun to build your own wheels when you know the principle. Your money has also improved, and Lavel has also improved. Come on, guys.

Vuex

The installation

npm install vuex --save



yarn add vuex





// Vuex relies on Promise, all you need to install is ES6-Promise



npm install es6-promise --save

yarn add es6-promise

Copy the code

Vuex introduction

Vuex is a state management mode developed specifically for vue.js applications.

store.js

import Vue from 'vue'

import Vuex from 'vuex'



Vue.use(Vuex)



export default new Vuex.Store({

state: {

count: 0.

message: 'Test information'

},

mutations: {

},

actions: {

},

modules: {

}

})



Copy the code

State ——> Data source of the driver application

1. Obtain the state data in store from the component
1.Get the state data in the store in the component



// The property is declared by evaluating the property and then using this.$store.state. Data source to get the data

computed: {

count () {

return store.state.count

}

}



Copy the code
How do you get multiple states?

If you want to obtain multiple state data, you can actually write multiple attributes in computed data to obtain state. However, when state changes, the computed attributes will be recomputed and the associated DOM will be updated, which greatly affects performance.

Fortunately, Vuex provides mapState helper functions to reduce unnecessary overhead

1.The first step is to introduce mapState

import { mapState } from 'vuex'



2.Use it computed

computed: mapState({

counts: state= > state.count,

//counts is a custom attribute: the state argument is state in STOte, and then passes state directly. Get the data source

addNumber (state) {

return this.numbers + state.count

}

})





3.Use custom attributes directly on the page

Copy the code

Getter

It is similar to computed, but has caching function.

Usage scenario: When a component needs the filtered state value, you can use filter in the component, then other components also need the filtered state value, you need to filter state again.

After using the getter, you can use the getter once to improve efficiency

export default new Vuex.Store({

state: {

count: 0.

message: 'Test information'.

arr: [1.2.3.4.5.6]

},

getters: {

filterArr: state= > {

return state.arr.filter(items= > items % 2= = =0)

}

}

})

Copy the code
mapGettersAuxiliary function

The mapGetters helper function simply maps the getters in the store to local computed properties:

Access getter values in the component
this.$store.getters. Custom attributes



When other components access the getters, the value remains2.4.6[Filtered

Copy the code

Mutation

Mutation is the only way to change the state of a Store.

It consists of event types and callback functions. The callback function is used to change the state, with the parameter state

Mutation of use:
  1. Events must be registered in mutation,
  2. It then passes through the componentStore.com MIT (Event name)Trigger to change the state of state
Note:

Store.com MIT parameters

Store.com MIT accepts two arguments

The first parameter is the event name in: store.mutation

The second parameter is: the load to be transferred

mutations: {

increment (state, n) {

state.count += n

}

}





store.commit('increment'.10)





Copy the code
mapMutationsAuxiliary function

The mapMutations helper function maps methods in the component to a store.mit call (requiring store injection at the root node).

Object’s submission method
mutations: {

increment (state, payload) {

state.count += payload.amount

}

}





mutations: {

increment (state, payload) {

state.count += payload.amount

}

}store.commit({

type: 'increment'.

amount: 10

})

Copy the code
Mutation Using techniques

Maintenance is difficult when the number of mutation types increases in collaborative development.

The official recommendation is to use the event type to process and improve development efficiency.

// mutation-types.js

export const SOME_MUTATION = 'SOME_MUTATION'



// store.js

import Vuex from 'vuex'

import { SOME_MUTATION } from './mutation-types'



const store = new Vuex.Store({

state: {... },

mutations: {

// We can use ES2015 style computed attribute naming to use a constant as the function name

[SOME_MUTATION] (state) {

// mutate state

}

}

})





Copy the code

Action

Action functions like Mutation,

Action Supports asynchronous operations
Mutation of Action submissions does not directly modify the state

Action takes parameters: a context object with the same methods and properties as the Store instance

The instance
const store = new Vuex.Store({

state: {

count: 0

},

mutations: {

increment (state) {

state.count++

}

},

actions: {

increment (context) {

context.commit('increment')

}

}

})

Copy the code
Distribute the Action in the component
this.$store.dispatch('xxx')

Copy the code
Executing an Action asynchronously
actions: {

incrementAsync ({ commit }) {

setTimeout((a)= > {

commit('increment')

}, 1000)

}

}

Copy the code
mapActionsAuxiliary function
Action also supports payloads
// Distribute in payload form

store.dispatch('incrementAsync', {

amount: 10

})



// Distribute as objects

store.dispatch({

type: 'incrementAsync'.

amount: 10

})

Copy the code

Module Segmentation

Store maintenance becomes difficult when all state objects are grouped into one large object. At this point, you can use modules to split multiple objects, and eventually mount the objects to a Modeule of the Store. Vuex allows you 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:

const moduleA = {

state: {... },

mutations: {... },

actions: {... },

getters: {... }

}



const moduleB = {

state: {... },

mutations: {... },

actions: {... }

}



const store = new Vuex.Store({

modules: {

a: moduleA,

b: moduleB

}

})



store.state.a // -> moduleA status

store.state.b // -> moduleB status

Copy the code

✨ feel good praise, help forward share the following, the original is not easy!


✨ Follow the wechat public account ‘front-end self-study Community’ for more information

💥 reply add group can join self-taught front-end group 💥