Previous: Vuex concise and clear Guide (Relearn front-end – VUE Part 2)
1. Directly modify the state difference from the COMMIT submission
- Common: Ability to modify variables in state, and responsiveness
- Difference: if passed in when vue creates store
strict: true
Open,Strict mode
, so any operation that changes the state will report an error if the function is not mutation
In general, we modify state via mutation
The advantages of using commit to mutation to modify state:
- Code structure is clearer
- Can reuse code, improve development efficiency
2. What should be paid attention to when the state is an object in Vuex
Because the object is a reference type, changing the property after replication will still affect the original data, which will change the state in the state, which is not allowed, so the object is copied by deep clone first and then modified.
3. Vuex state is used in batches for components
Use the mapState helper function to mix state into a computed object using the object expansion operator
import {mapState} from 'vuex' export default{ computed:{ ... mapState(['a','b']) } }Copy the code
4. How do I derive some state from state for multiple components to use
- With the getter property, comparable to computed property in Vue, derived state changes only when the original state changes.
- The getter takes two arguments, the first is
state
The second isgetters
Can be used to access other getters.
Const store = new vuex. store ({state: {a: 10, b: 10, c: 0.7,}, getters: {total: state => { return state.a * state.b }, getTotal: (state, getters) => {// getters return state.c * getters. Total}},});Copy the code
These derived transitions can then be accessed in the component using the computed property computed through this.$store.getters. Total.
computed: {
total() {
return this.$store.getters.total
},
getTotal() {
return this.$store.getters.getTotal
}
}
Copy the code
5. Use getters to filter state
Pass parameters to the getter by making the getter return a function. Then, the parameters are used to determine the state that meets the requirements in state.
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
getTodoById: (state) => (id) =>{
return state.todos.find(todo => todo.id === id)
}
},
});
Copy the code
Then in the component can be used to calculate attribute computed by enclosing $store. Getters. GetTodoById (2) to access these derived in shift.
computed: { getTodoById() { return this.$store.getters.getTodoById }, } mounted(){ console.log(this.getTodoById(2)) // { id: 2, text: '... ', done: false } }Copy the code
6. Alias getter attributes in batches in the component
Use the mapGetters helper function to mix getters into a computed object using the object expansion operator
import {mapGetters} from 'vuex' export default{ computed:{ ... MapGetters ({myTotal:'total', // alias myTotal myDiscountTotal:'discountTotal',})}}Copy the code
7. How to change the state of state?
Mutations are the first mutation to be registered in mutations
const store = new Vuex.Store({ state: { number: 10, }, mutations: {SET_NUMBER(state,data){// state. Number =data; }}});Copy the code
Use this. codestore.mit to commit mutation in the component to change the number
this.$store.commit('SET_NUMBER',10)
Copy the code
8. Difference between Action and mutation
- The action submitted is mutation, and
Not a direct state change
. Mutation can change the state directly. action
Can contain anyasynchronous
Operation.mutation
Can only besynchronous
Operation.- The submission method is different; action uses this.
store.commit
(‘SET_NUMBER’,10) to commit. - The receiving parameters are different, and the first parameter of mutation is
state
And the first argument to action iscontext
And it contains
{state, // equivalent to 'store.state' or local state rootState in modules, // equivalent to 'store.state', Commit, // equivalent to 'store.mit' dispatch, // equivalent to 'store.dispatch' getters, // Equivalent to 'store.getters' rootGetters // Equivalent to' store.getters', only exists in modules}Copy the code
9. How do I know when an asynchronous action ends
Return the Promise in the action function, and then handle the submission
actions:{ SETA({commit},data){ return new Promise((resolve,reject) =>{ setTimeout(() =>{ commit('SET_NUMBER',10); resolve(); },2000) }) } } this.$store.dispatch('SETA').then(() => { // ... Action SETA is executed})Copy the code
10. Vuex has two actions, actionA and actionB, both of which are asynchronous operations. To submit actionA in actionB, you need to execute actionB after the actionA processing is completed.
Use ES6 async and await to implement.
actions:{ async actionA({commit}){ //... }, async actionB({dispatch}){await dispatch ('actionA')// Wait for actionA to complete //... }}Copy the code
11. Simple use of Vuex module
Why modularity?
Because of the use of a single state tree, all the states of the application are grouped into one large object. When the application becomes very complex, the Store object can become quite bloated.
So store is divided into modules. Each module has its own state, mutations, actions, getters, and even nested submodules, which are divided in the same way from top to bottom.
Create moduleA.js and moduleb. js files in the module file. Write in the file:
const state={
//...
}
const getters={
//...
}
const mutations={
//...
}
const actions={
//...
}
export default{
state,
getters,
mutations,
actions
}
Copy the code
Then index.js will introduce the module
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
import moduleA from './module/moduleA'
import moduleB from './module/moduleB'
const store = new Vuex.Store({
modules:{
moduleA,
moduleB
}
})
export default store
Copy the code
12. State, the first parameter received by the getters and mutations in the module, is global or modular?
The first parameter state is the module’s state, that is, local state.
How do I access the global state and getter in a module
- in
getter
Can pass the third parameterrootState
Global state can be accessed through the fourth parameterrootGetters
Access the global getter. - in
mutation
In theCan not be
Access to the global SATAT and getterThe state of the local
. - in
action
Context, the first parameter incontext.rootState
Access the global state,context.rootGetters
Access the global getter.
14. How are attributes used in components
- Directly through
this.$store.getters
andthis.$store.state
To access the getter and state in the module. - Directly through
this.$store.commit('mutationA',data)
Mutation in the commit module. - Directly through
this.$store.dispatch('actionA,data')
Submit the actions in the module.
Commit global mutation and action within the module with namespace
Pass {root: true} as the third argument to Dispatch or commit.
- this.$store.dispatch(‘actionA’, null,
{ root: true }
) - this.$store.commit(‘mutationA’, null,
{ root: true }
)
Register global actions in the module of the namespace
actions: { actionA: { root: true, handler (context, data) { ... }}}Copy the code