State management in the framework
Chapter 1 Vuex (Please see the Map of god first)
Single data flow
Vuex management process
The status management application consists of three parts:
- State, the data source that drives the application;
- View, to declaratively map state to the view;
- Actions, in response to changes in state caused by user input on the view.
Enter the actual combat
- In using global installation vue vUE – CLI
- Use the vue family bucket command vue create project name
- To install vuex, run yarn add VUex
1. Open the main.js file, which is the entry to the vue project. In this file, create the vue instance and mount it to other module plug-ins
import router from './router/'
import store from './store/'
new Vue({
store,
router,
render(h) {
return h(App)
}
}).$mount('#app')
Copy the code
2. Create the directory store in the same directory as Pages and create index.js
- Import the appropriate package and use Vuex on Vue
- Create Vuex instance new vuex.store ({})
- Here comes the key part: define the Vuex soul parts state, getters, mutation, Action, and Module in the example, which will be explained later. Let’s look at my simple layout first
import Vue from 'vue'
import Vuex from 'vuex'
import http from '.. /utils/http'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
data: {}},getters: {},mutations: {
setFirstData(state, result) {
state.data = result
},
},
actions: {
async loadFirstData({commit}, params) {
let result = await http.get(params.firstReq)
commit('setFirstData', result)
},
},
module: {state tree}})export default store
Copy the code
3. After seeing the general structure, it can help beginners to build quickly. Of course, each individual module can also be defined separately outside, and then introduced into the example. Let’s talk about the roles of each of the five cores.
state
Vuex uses a single state tree, with an object wrapped around all the states you define in a state tree. We can also use module when the data is large and divided into different modules, which will be discussed later.
getter(getters)
Before learning Vuex, you already know the computational properties in Vue, which are used to monitor whether the state in data changes. In fact, getters is similar to computed properties. You can define multiple methods in this object, and when the data in state changes, the function executes and returns the new state. The return value of a getter is cached based on its dependency and is recalculated only if its dependency value changes. Note: The getter defines a function, and one of the arguments to the function is state, and the state defined above. A Getter can also accept another Getter as a second argument.
mutation(mutations)
In Vuex, there is only one way to change the state in a store, and that is mutation. In mutation, you can define multiple methods whose operations ultimately change the properties you defined in state. These methods accept state as the first argument, and when you want to pass in a parameter to the method, the second argument is: The payload can be an object or a method of some other primitive type (state,payload) {} note: mutation does define many methods, but you can only call them from store.mit (‘ method name ‘). Mutation must be a synchronous function, not one of the three calls supported by asynchronous operations in the method
store.commit({
type: 'increment'.amount: 10
})
store.commit('increment', {
amount: 10
})
store.commit('increment'.10)
Copy the code
Action (See vuex website for details)
Mutation can only perform synchronous operations. However, we often need to request interface resources for asynchronous operations. Action is where mutation comes in, but there are a few caveats to using action.
- Do not try to change the state in state directly in action. And neither can you. (# ^. ^ #)
- The action commits mutation rather than directly modifying the status.
- Via context.mit (submit a mutation method)
Excerpt official documents: 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.
Of course, you can also use ES6’s destruct assignment {xx} to deconstruct the commit from the context. How to call the action method in the required component:
store.dispatch('increment')
// Distribute in payload form
store.dispatch('incrementAsync', {
amount: 10
})
// Distribute as objects
store.dispatch({
type: 'incrementAsync'.amount: 10
})
Copy the code
Module (See the website for more details here)
Vuex maintains a single state tree, but when the tree is too large, it becomes difficult to maintain and extract the required attributes. At this time, a single state tree can be divided into multiple modules, just like branches of the tree. In each single branch, there are still state, mutation, getter, action and module, and multiple sub-modules can be nested in each module.
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
For getters inside the module, the root node state is exposed as a third parameter:
const moduleA = {
// ...
getters: {
sumWithRootCount (state, getters, rootState) {
return state.count + rootState.count
}
}}
Copy the code
How is it used in components
With the definition and some rules inside the Store mentioned above, it is time for practitioners to focus on how to use vuEX managed states and methods in components. There are also four methods of pairing in Vuex, which structure is required and which mapState is required
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// Arrow functions make code more concise
count: state= > state.count,
// Pass the string argument 'count' equal to 'state => state.count'
countAlias: 'count'.// In order to be able to use 'this' to get local state, you must use regular functions
countPlusLocalState (state) {
return state.count + this.localCount
}
})}
Copy the code
mapGetter
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// Mix getters into a computed object using the object expansion operator. mapGetters(['doneTodosCount'.'anotherGetter'.// ...])}}Copy the code
mapMutations
import { mapMutations } from 'vuex'
export default {
// ...methods: { ... mapMutations(['increment'.// Map 'this.increment()' to 'this.store.com MIT ('increment')'
// 'mapMutations' also supports payloads:
'incrementBy' // Map 'this.incrementBy(amount)' to 'this. codestore.com MIT ('incrementBy', amount)'
]),
...mapMutations({
add: 'increment' // Map 'this.add()' to 'this.store.mit ('increment')'}}})Copy the code
mapActions
import { mapActions } from 'vuex'
export default {
// ...methods: { ... mapActions(['increment'.// Map 'this.increment()' to 'this.$store.dispatch('increment')'
// 'mapActions' also supports payloads:
'incrementBy' // Map 'this.incrementBy(amount)' to 'this.$store.dispatch('incrementBy', amount)'
]),
...mapActions({
add: 'increment' // Map 'this.add()' to 'this.$store.dispatch('increment')'}}})Copy the code