The data transfer and reference problem of calling state, getters, mutations, actions, modules of Vuex in component

Posted by SWI03 on Fri, 18 Feb 2022 14:53:59 +0100

Why should bloggers summarize these questions of the title
       1. Before Vue 2.0, in the face of small front-end single page rich application (SPA) applications, simple methods such as localStorage cache were used to solve the problem of data transmission. In the face of relatively large-scale applications, the above simple methods such as localStorage can no longer meet the requirements, so Vuex needs to be used to know the specific flow problems between pages more conveniently.

       2. When learning Vuex, we simply look at the problem of value transfer and find that it is not too difficult, just some simple commit, dispatch, etc. But after dividing the module, how to transmit the reference problem when facing the data transmission between modules, and calling mutaions, actions and other methods in the component. I felt a lot of problems for a while. My mind was full of dizziness, so I wrote such a blog post after unremitting efforts.

      3. The following content is purely manual practice, which is convenient for everyone to view and summarize, and it is also convenient for you to view in the future. If you have any questions, please comment and point them out, and then I'll correct them. If there is any mistake, please spray gently. Thank you
 

 

1.State

Personal point of view: data in state, Vuex can only be submitted through mutations, basically in the component, and the relevant mutations, actions and so on can meet the requirements. Therefore, personal feel that state reads in the component without special circumstances, it doesn't make much sense.

<!-- moduleA--modular A -->
const moduleA = {
    state:{
        count:888
    }
}
 
<!-- Component, get State Data -->
<template>
    <div>
        <span>Basic acquisition method:(Obtained in this way,Can be written in computed Within calculation attribute,It doesn't look complicated)</span>
        <span>Get parent store Medium state Lower count Value:{{$store.state.count}}</span>
        <span>obtain moduleA In the module state Lower count Value:{{$store.state.moduleA.count}}</span>
        <hr>
        <span>mapState Auxiliary function acquisition method:</span>
        <span>Get parent store Medium state Lower count Value:{{count}}</span>
        <span>obtain moduleA In the module state Lower count Value:{{countA}}</span>
    </div>
</template>
 
<script>
    import {mapState} from 'vuex';
    export default {
        name: "Body",
        computed: {
            //Get the count value under state in the parent store
            ...mapState(['count']),
            //Get the count value under state in moduleA module
            ...mapState({
                countA:state=>state.moduleA.countA
            }),
            
        }
    }
</script>

 

2.Getters
The parameter order of rootState and rootGetters should not be reversed. state must be in front and getter in the back. This is the default parameter transfer order of vuex.

In the rootGetters parameter, including the root store and all getters methods in the module, directly rootGetters The method name can be obtained.

There is such a scenario: Vuex defines a data list, which is an array. If you only want to get data less than 10, the easiest way to think of may be to filter in the calculation properties of the component. There's no problem with that. However, if there are other components that also need filtered data, we have to completely copy the calculated code, and when the filtering method needs to be modified, each component used has to be modified, which is obviously not the result we expect. It's convenient to extract multiple things from geters.  

Personal view: for the above scenario, getters is actually a common method. There is actually no relationship between getters and changes / actions. Therefore, as long as getters can get the state parameter value of the root store or brother module and the getters method, its goal has been achieved
 

//In module
const moduleA = {
    getters:{
        showStateData(state,getters,rootState,rootGetters){
            console.log('Current module count value:'+state.countA);
            console.log('root store Medium count value:'+rootState.count);
            console.log('Brother module moduleB Medium countB value:'+rootState.moduleB.countB);
            console.log('root store The name in is increNum of getters method:'+rootGetters.increNum);
            console.log('Brother module moduleB The name in is moduleBGetter of getters method:'+rootGetters.moduleBGetter);
        },
======================================================================================================
        //Here it is. This getters is used when there are parameters in the following components
        moduleAGetter:(state)=>(param,name)=>{
            console.log(param)
            console.log(name)
        }
        
        //Equivalent to
        moduleAGetter(state) {
            return function (param,name){
                console.log(param);
                console.log(name);
            }
        }
    
    }
}
 

 

//How to transfer parameters when used in components
<template>
    <div>
        I am Body<hr>
        <button @click="moduleAGetter">getters get data</button>
        <button @click="changeNameGetter">Renamed getters get data</button>
    </div>
</template>
 
<script>
    import {mapGetters} from 'vuex';
    export default {
        name: "Body",
        methods: {
            //1. Generally, there are two situations:
            commonGetter(){
                //(1) no parameter reference getter
                return this.$store.getters.moduleAGetter;
                //(2) if there is a parameter reference getter, it should be passed in this way (it can also be passed as an object). Or pass it like this: commonGetter(id,name) {...}
                return this.$store.getters.moduleAGetter(996,'Mr.Liu');//Please check the moduleAGetter method defined in the module above.             
            },
 
            //2.mapGetters auxiliary functions are divided into the following three cases:
            //(1) no parameter reference getter
            ...mapGetters(['moduleAGetter']),
            //(2) there is no parameter reference getter, in case of renaming
            ...mapGetters({
                changeNameGetter:'moduleAGetter'
            }),
            //⑶ there is a parameter reference getter
            //We haven't found how mapGetter uses auxiliary functions to transfer parameters yet. If you know, you are welcome to add
            
        }
    }
</script>
 

3.Mutations
The only purpose of mutations is to modify the data in state. It is impossible for him to get the getters, variations, actions, etc. of a store or brother module.

Personal opinion: mutaions can only modify the data in the state, and it should only modify the data in the state of this module, so it can't get the state values of the root store and brother modules, but can only get the state values of its own modules

If you use changes to modify the attributes in the object in state, such as obj {id:1,name:'Mary'}, and modify the existing attributes of the object, it will be displayed in response. If there is no attribute in the modified attribute object, such as state When obj ['address'] ='La 'is modified, this operation is not responsive. Vue Set (state. Obj, 'address',' La ') is a responsive method.

Use delete state obj. Address is not responsive when deleting an object property. Vue Delete (state. Obj, 'address') is a responsive way to delete.
 

//In module
const moduleA = {
    mutations:{
        moduleAMutation(state){
            console.log('Current module count value:'+state.count);
        },
 
        // When other methods are used (described in the methods below), the receiving parameters are different (the name is defined here as count, which is not 5, but an object)
        // The parameter in the movements is called the payload of the movement
        // moduleAMutation(state, count){
        //     console.log('count value of current module: '+ state.count);
        // }
        // This definition is recommended here
        // moduleAMutation(state, payload){
        //     //Here, the payload receives an object of {type: 'moduleAMutation', count: 5}    
        //}
=======================================================================================================
        //paramMutation is used when parameters are passed in the following components
        paramMutation(state,obj){
            console.log(obj.id);
            console.log(obj.name);
            console.log('A In the module count Attribute value:'+state.count);
        },
    }
}
 
<!--How to transfer parameters when used in components-->
<!--At present, the individual has completed the research, and there are many problems in the module mutaion In, the default first pass parameter is state,This is Vuex Dead, the rest of the custom parameters-->
<!--Personal research has found that we can only deliver one. If you want to pass more than one parameter, you can only pass it as an object. If there are errors or corrections, please comment and modify-->
<template>
    <div>
        I am Body<hr>
        <button @click="commonMutation">⑴Basics mutations get data</button>
        <button @click="moduleAMutation">⑵auxiliary function  mutations get data</button>
        <button @click="changeNameMutation">⑶Rename mutations get data</button>
        <button @click="paramMutation({id:996,name:'Mr.Liu'})">⑷Ordinary with parameters mutations get data</button>
        <button @click="paramMapMutation({id:996,name:'Mr.Liu'})">⑸Parametric auxiliary function mutations get data</button>
 
    </div>
</template>
 
<script>
    import {mapGetters,mapActions,mapMutations} from 'vuex';
    export default {
        name: "Body",
        methods: {
          ⑴commonMutation(){
                this.$store.commit('moduleAMutation');
            },
          ⑵...mapMutations(['moduleAMutation']),
          ⑶...mapMutations({
                changeNameMutation:'moduleAMutation'
            }),
          ⑷paramMutation(obj){
                this.$store.commit('moduleAMutation',obj);
            },
          ⑸...mapMutations(obj){//Pass parameters and use auxiliary functions. The parameters can only be passed to the place where < button @ Click = "parammapmutation ({ID: 996, name: 'Mr. Liu'})" > < button > is called after I have studied them
                paramMapMutation:'moduleAMutation',
            })
 
           // There is another style of submissions using commit, which is as follows:
           // Other styles:
           // It can also be written as follows (but the receiving parameters are a little different where the changes method is defined. See above)
           // this.$store.commit({
           //     type: 'moduleAMutation',
           //     count: 5 / / parameter
           // })
        }
    }
</script>
 
<style scoped>
 
</style>
 

4.Actions
Actions is mainly used to ① submit changes ② perform asynchronous operations

Vuex provides the rootState parameter for Actions to obtain the data in the root store and brother modules.

Personal view: since the modules have been divided and the data of each module should be independent of each other, it is impossible for the actions in module A to submit module B or the changes in the store. Therefore, the actions part can only obtain the state data in the root store or brother module
 

//In module
const moduleA = {
    actions:{
        getStateData({state,commit,getters,rootState,rootGetters}){
            console.log('Current module count value:'+state.count);
            console.log('root store Medium count value:'+rootState.count);
            console.log('Brother module moduleB Medium count value:'+rootState.moduleB.count);
            rootGetters.increment();//Get the getters method named increment in the root store
            getters.moduleAIncrement();//Get the getters method in the current module. If you pass parameters, you can pass them directly in parentheses. You can make multiple parameters or an obj object
        },
=======================================================================================================
       //moduleAAction is used when parameters are passed in the following components
        moduleAAction({state,commit,rootState},obj){//An obj object parameter is passed here
            console.log(state)
            console.log(obj.id);
            console.log(obj.name);
            console.log('A In the module count Attribute value:'+state.count);
            console.log('In parent module count Attribute value:'+rootState.count);
            console.log('Brother module moduleB Medium count attribute:'+rootState.moduleB.count);
            commit('moduleAIncr',obj.id);//Here is the id parameter of the obj object. Continue to submit it to mutaions for use
        },
 
        //!!! Important: Vue does not recommend the direct state data operation in actions. It is recommended to modify the data in state through mutations ()
        demoAction(context,payload){// Here, payload is an object parameter, similar to obj object (in mutations, the parameter is called payload, so payload is also defined here, and the low obj definition is discarded)
            context.commit('mutations Name of');//Context means context
        }
 
 
        // ES6: Deconstruction assignment of objects
        //Tip: you can write a context parameter directly.
        //The above parameter methods, such as modulaaction ({state, commit, rootstate}), are the deconstruction and assignment of objects in ES6 (equivalent to where each object in the context is directly placed, eliminating the need to write multiple such codes such as context.state and context.commit)
    },
    mutations:{
        //The mutations method with the additional name of moduleancr here is only used for reference in the following part
        moduleAIncr:(state,num)=>{
            console.log(num);
            state.count +=num;
            console.log(state.count)
        }
    }
}

 
<!--When used in components, how to pass parameters (in fact, it is the same as above) Mutations (same as pass on parameter, no difference)-->
<template>
    <div>
        I am Body<hr>
        <hr>
        <button @click="commonAction">⑴Basics actions get data</button>
        <button @click="moduleAAction">⑵auxiliary function  actions get data</button>
        <button @click="changeNameAction">⑶Rename actions get data</button>
        <button @click="paramAction({id:996,name:'Mr.Liu'})">⑷Ordinary with parameters actions get data</button>
        <button @click="paramMapAction({id:996,name:'Mr.Liu'})">⑸Parametric auxiliary function actions get data</button>
    </div>
</template>
 
<script>
    import {mapGetters,mapActions,mapMutations} from 'vuex';
    export default {
        name: "Body",
        methods: {
          ⑴commonAction(){
                this.$store.dispatch('moduleAAction')
            },
          ⑵...mapActions(['moduleAAction']),
          ⑶...mapActions({
                changeNameAction:'moduleAAction'
            }),
          ⑷paramAction(id,name){
                this.$store.dispatch('moduleAAction',id,name);
            },
          ⑸...mapActions({//Pass parameters and use auxiliary functions. The parameters can only be passed to the place where < button @ Click = "parammapaction ({ID: 996, name: 'Mr. Liu'})" > < button > is called after I have studied them
                paramMapAction:'moduleAAction'
            })
 
        }
    }
</script>
 
<style scoped>
 
</style>
 

5.Modules
See Part II: 13 Namespace in vuex module named

Summarizing the above knowledge points is only for your convenience. I also hope to help you who are reading this blog. There may be some mistakes based on your own summary. I hope you can understand and comment. Thank you.

Attachment: Vue contents:

    1. Value transfer between Vue components 2 V-model is used in components

    3.Vue.js actual combat questionnaire WebApp project 4 Vue cli + webpack build Vue development environment

    5. Vue simple problem summary (continuous update...)                  6. Bus for data communication between Vue components

    7. Vue router navigation hook (with Demo example) 8 ES6 difference between arrow function and ordinary function

    9. Use of vuex 10 Auxiliary functions such as mapState, mapGetters, mapMutations and mapActions in vuex components

   11. The data transfer and reference problem of calling state, getters, mutations, actions, modules of Vuex in component

   12.Vuex namespace 13 Use of Vue Axios
Transfer from https://blog.csdn.net/lzb348110175/article/details/89351059

Topics: Front-end Vue