Author: Ziksang, a mixed yuan thunderbolt player

Vuex official website of professional terms, let some people still feel confused, do some practical scenarios to show you

  • State is used to share data stores
  • Mutation is used to register changes in data state
  • Getters is used to filter shared data
  • Action Resolves asynchronously changing shared data

These four characteristics are the core, how to use how to use

We’re gonna do what we agreed on

At this time, the demonstration method is still using the official vue-CLI Webpack version

We create a vuex folder under the SRC directory, create the index respectively. Js, mutations, js, the state, js, getters, js, actions. Js

Benefits:

In this way, we can file the four features separately, so that we can be more clear and clear

We put these four features into index.js to implement store

You can also register stores in each component at the same time by introducing a column store called the index.js folder into main.js

How is state used?

In the page, the title must be necessary, the title of each component page must be different, then how do we get the title, the title is suitable for where, according to each page switch, and change the title, this is involved in the communication between components and components

We can specify a data value first in state.js

Export default{title: "home"}Copy the code

So how do we get the title value in the home page

So let’s add new Vue to mian.js, bind the instance code of the title scope and we’re doing data listening in computed, so now we can get the last step of state.title from the store, Let’s do the {{title}} binding again in index.html

index.html

<title>{{title}}</title>
Copy the code

So let’s run it now, open up dev-tools and you’ll see

The title data is already shared globally

How is Matutions used

Application Scenarios: If we want to change the top-level shared data, we should do it with matutions. If you do a public account, the backend will usually give you some parameters on the connection, say SID, CK, TM, or something else that you want to store in state. If you do that, So let’s register events through matutions, which I’m doing for demonstration purposes

Note: For Vuex, I only recommend storing state in a single page for component-to-component communication. It is not appropriate to put some state in a page

state.js

Export default{START_PARMA: {}, title: "home"}Copy the code

START_PARMA is used to store the data of the above connection parameters, which we had to decide before

mutations.js

export default{
    getParam (state,Object) {
       state.START_PARMA = Object
    }
}
Copy the code

We register an event to change state data, taking the state object as the first argument and passing in the second argument

  • GetParam officially says type, which is actually the registered event name
  • It can be a single parameter
  • If it’s multiple arguments, we’ll put it in as an object, and if you write two arguments, you’ll get an error
export default { name : 'advertisement', created () { const keyCode = sessionStorage.keyCode = getQueryString('keyCode') const keyWord = sessionStorage.keyWord =  keyCode.split("_")[0] const hunterCode = sessionStorage.hunterCode = keyCode.split("_")[1] const sid = sessionStorage.sid= getQueryString('sid') const ck = sessionStorage.ck = getQueryString('ck') const tm = sessionStorage.tm = getQueryString('tm') this.$store.commit('getParam',{ keyCode, keyWord, hunterCode, sid, ck, tm }) } }Copy the code

We create our own view and create intercepts the argument in created. Since store is registered to each component, we use this.$store to access the view. It’s using es6 syntax

And then you’ll see

The captured state is then put into an object that we can use

How do getters work

So a getter is a way of doing some filtering and modification of the data in the state

So let’s say State has some data like this

state.js

people : [
        {name : 'ziksang1',age:21},
        {name : 'ziksang2',age:10},
        {name : 'ziksang3',age:30},
        {name : 'ziksang4',age:40},
        {name : 'ziksang5',age:50},
        {name : 'ziksang6',age:30},
        {name : 'ziksang7',age:80}
    ]
Copy the code

If we define this data, and we want to filter out people older than 30 from this data, and then return it, we can use the getter, and the getter here means to filter the top level of the VUEX data without changing the original data in the state

getters.js

export default{
    changePeople: (state) =>{
        return state.people.filter(item=>{
            if(item.age>30){
                return true
            }
        })
    }
}
Copy the code

Ok, so how do we apply that, we just say in the component, okay

created () {
   console.log(this.changePeople)
},
computed : {
            changePeople () {
                return this.$store.getters.changePeople
            }
        },
Copy the code

Well, we can turn on the mission and take a look at the data,

What do you want to do with the data then that’s up to you

How do I use action?

Action. Is used to solve the asynchronous process to change the state data, I want to say, then I directly write in the inside of the matution not on the line, then you can try, because the matution is directly synchronized operation

mutations.js

export default{
    getParam (state,Object) {
       setTimeout(()=>{
            state.START_PARMA = Object
       },1000)
    }
}
Copy the code

Take the above example. If you conduct an asynchronous operation in mutations, you will find that it is useless and will not have any effect. What should you do instead, do it through the process of action->mutations-> States

action.js

export default {
    getParamSync (context,Object) {
        setTimeout(()=>{
            context.commit('getParam',Object)
        },3000)
    }
}
Copy the code

Write a getParamSync function, the first parameter is the context, the context is a store object, you can also destruct it, the second parameter is the received parameter that we want to write, To change the triggering events, and then change the state through mutation, which is easy to understand

And then we just call it that way in the component

 this.$store.dispatch('getParamSync',{
                keyCode,
                keyWord,
                hunterCode,
                sid,
                ck,
                tm
            })
Copy the code

What about action? Sometimes when we make a request to the background, the first AJAX return value is used for the next action distribution

We can use promises for asynchronous processing

actions.js

export default { getParamSync (context,Object) { return new Promise((reslove,reject)=>{ setTimeout(()=>{ Context.com MIT ('getParam',Object) return reslove(' success ')},3000)})}, context.com MIT ('getParam',Object) return reslove(' success ')}, context.com changetitleSync ({commit},title){ setTimeout(()=>{ commit('changetitle',title) },3000) } }Copy the code

After getParamSync uses the new Promise, return ‘success’ in Resolve and issue a changetitleSync action method that changes the title

mutations.js

export default{
    getParam (state,Object) {
       state.START_PARMA = Object
    },
    changetitle (state,title){
        state.title = title
    }
}
Copy the code

Then register a changetitle changetitle type

Group middle call

created(){
 this.$store.dispatch('getParamSync',{
                keyCode,
                keyWord,
                hunterCode,
                sid,
                ck,
                tm
            }).then((res)=>{
                this.$store.dispatch('changetitleSync',res)
            })
}
Copy the code

We can make a chain call in the component to solve the asynchronous callback, and then we can overlay the action with the action to form a composite action

About other auxiliary uses

  • MapState helper function
  • MapGetters helper function
  • MapMutations auxiliary function
  • MapActions helper function

You can refer to the website of Vuex to read it. There is no need for me to re-explain it here

conclusion

In vuex, where do I think vuex is better used?

It is only suitable for combination passing between components within a view, not across pages, but can be shared and initialized again in order not to refresh the page for the user.

Not suitable for use there

In their own writing some Ui components or open source for everyone to use, does not apply to write in vuex should expose receives Props, triggered by $emit events, some key global state, not suitable for storage vuex, you can choose the localStorage and sessionStorage

To learn more about VUE, please subscribe to my Nuggets column

Dredge front-end development engineer, like to study, love to share and explain teaching, please wechat zzx1994428 QQ494755899

If you support me to continue to create and feel fruitful, please send me a tip

If reproduced please mark from @ mixed yuan thunderbolt hand Ziksang