Take a look at the basic structure of VUEX:

export default new Vuex.Store({
  state: {
  user: {name:'clying'}},getters: {},mutations: {},actions: {}})Copy the code

How to read the name of user? Up until the day before yesterday, I used this.$store.state.user.name. If you use it this way, then you are OUT like me!! Vuex getters are for reading data! Vuex’s mutations and Actions are used to change data, one asynchronously and the other synchronously. That’s all I knew before, but! BUT!!! When I was writing this article, I realized that I was just an armchair strategist.

this.$store.user = JSON.parse(JSON.stringify(user))
Copy the code

Emmmm, although it knows the conversion of JSON format, still doesn’t realize the power of VUex! Take a look at the diagram above. Vuex uses dispatch to call the actions method, actions uses commit to call the mutations method, and mutations assigns values to variables in the store. Then I’ll say getters. The component retrieves shared data by accessing methods in getters. This is vuex’s real data assignment reading! This is a one-way data flow event in English. Here is a simple example:

// The data obtained by calling the interface in the component is stored in the store user

// Assign component
this.$store.dispatch("UPDATE_USER", data);  //1. Trigger actions, UPDATE_USER method name

//store
export default new Vuex.Store({
    state: {user:{}
    },
    getters: {user:user= > state.user;        //4. Getters exposed to the component to read
    },
    mutations: {UPDATE_USER_MU:(state,userInfo) = > {
            state.user=userInfo;                    //3. Actually change the value of user in state}},actions: {UPDATE_USER:({commit},userInfo) = > {
            commit('UPDATE_USER_MU',userInfo);      / / 2. com MIT trigger mutatios}}})// Other components
cosnolse.log(this.$store.getters.user)      //5. Read the value of vuex

Copy the code

See this, the insight is to look carefully at the document emmmm… Friends come on!!