[vue log-vuex]VueX (Vue state management mode)

First, get to know VueX

1.1 AboutVueX

VueXIt is Vuea state management tool suitable for use in project development. Imagine that if you frequently use component parameter transfer to synchronize datavalues in a project development , once the project becomes very large, managing and maintaining these values ​​will be quite tricky work. To this end, Vuea unified management tool is provided for these values ​​frequently used by multiple components VueX. In VueXexisting Vueprojects, we only need to define these values ​​in VueX, and then they can be used in Vuethe components of the entire project.

1.2 Installation

Since it VueXis done VueCliafter learning , please refer to the VueCli 2.xbuilt directory for the list of items that appear below .

The premise of the following steps is that you have completed the construction of the Vue project and moved to the file directory of the project.

  • Npm install Vuex
npm i vuex -s
  • Add a new storefolder under the root directory of the project and create it in the folderindex.js

At this point, the srcfolder of your project should look like this

│  App.vue
│  main.js
│
├─assets
│      logo.png
│
├─components
│      HelloWorld.vue
│
├─router
│      index.js
│
└─store
       index.js

1.3 Use

1.3.1 Contents storeunder initializationindex.js

import Vue from 'vue'
import Vuex from 'vuex'

//挂载Vuex
Vue.use(Vuex)

//创建VueX对象
const store = new Vuex.Store({
    
    
    state:{
    
    
        //存放的键值对就是所要管理的状态
        name:'helloVueX'
    }
})

export default store

1.3.2 storeMount to the Vueinstance of the current project

Open main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
    
    
  el: '#app',
  router,
  store,  //store:store 和router一样,将我们创建的Vuex实例挂载到这个vue实例中
  render: h => h(App)
})

1.3.3 Use Vuex in components

For example, in App.vue, we need to use the name defined in the state to display in the h1 tag

<template>
    <div id='app'>
        name:
        <h1>{
    
    {
    
     $store.state.name }}</h1>
    </div>
</template>

Or to use in component method

...,
methods:{
    
    
    add(){
    
    
      console.log(this.$store.state.name)
    }
},
...

Note, please do not change statethe value of the status here , it will be explained later

1.4 Install VueDevtools

In Vue project development, you need to monitor various values ​​in the project. In order to improve efficiency, Vue provides a browser extension-VueDevtools.
0
When learning VueX, it is more necessary to use this plug-in. Regarding the use of this plug-in, you can move to the official website, so I won’t repeat it here.

Second, the core content in VueX

In the VueX object state, there are not only members , but also statethe method set used to manipulate the data, and the method set that needs to statebe processed when we need to align the data.

Member list:

  • state storage state
  • Mutations state member operations
  • getters process state members to the outside world
  • actions asynchronous operations
  • modules Modular state management

2.1 VueX workflow

1
First of all, Vueif a component VueXneeds to make a request to the backend during the process of calling a certain method, or when an asynchronous operation occurs, the method in dispatchVueX is required actionsto ensure the synchronization of the data. It can be said that actionthe existence is to allow mutationsthe method in the asynchronous operation to work.

If there is no asynchronous operation, then we can directly submit the method written by ourselves in the Mutations in the component state to achieve statethe operation on the member. Note that 1.3.3it is mentioned in the section that it is not recommended to directly manipulate statethe members in the component, because the direct modification (for example this.$store.state.name = 'hello':) cannot be VueDevtoolsmonitored.

The last modified state member will be rendered to the original position of the component.

2.2 Mutations

Mutations are a collection of methods for manipulating state data, such as modifying, adding, and deleting the data.

2.2.1 How to use Mutations

mutationsThe methods have default parameters:

([state] [,payload])

  • stateIs in the current VueXobjectstate
  • payloadThis method is used to pass parameters when it is called

For example, if we write a method, when it is executed, the name value in the following example can be changed to "jack", we only need to do this

index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex({
    
    
    state:{
    
    
        name:'helloVueX'
    },
    mutations:{
    
    
        //es6语法,等同edit:funcion(){...}
        edit(state){
    
    
            state.name = 'jack'
        }
    }
})

export default store

In the component, we need to call this like this mutation-for example, in one of App.vue method:

this.$store.commit('edit')

2.2.2 Mutation passing value

In the actual production process, you will encounter the need mutationto carry some parameters to the method when submitting a certain .

When a single value is submitted

this.$store.commit('edit',15)

When you need to submit multiple parameters, it is recommended to put them in an object to submit:

this.$store.commit('edit',{
    
    age:15,sex:'男'})

Receive mounted parameters:

edit(state,payload){
    
    
     state.name = 'jack'
      console.log(payload) // 15或{age:15,sex:'男'}
  }

Another way to submit

this.$store.commit({
    
    
    type:'edit',
    payload:{
    
    
        age:15,
        sex:'男'
    }
})

2.2.3 Adding and deleting members in state

In order to cooperate with Vue's responsive data, we should use the methods provided by Vue to operate in the method of Mutations. If deleteor xx.xx = xxform to add or delete, the data Vue can not respond in real time.

  • Vue.set sets the value of a member for an object, if it does not exist, add it

    For example, add an age member to the state object

    Vue.set(state,"age",15)
    
  • Vue.delete delete member

    Delete the age member just added

    Vue.delete(state,'age')
    

2.3 Getters

stateThe members can be processed and passed to the outside world

The method in Getters has two default parameters

  • state The state object in the current VueX object
  • getters The current getters object, used to use other getters under the getters

E.g

getters:{
    
    
    nameInfo(state){
    
    
        return "姓名:"+state.name
    },
    fullInfo(state,getters){
    
    
        return getters.nameInfo+'年龄:'+state.age
    }  
}

Call in component

this.$store.getters.fullInfo

2.4 Actions

Because mutationof the asynchronous operation directly in the method, it will cause the data to become invalid. So Actions are provided to specifically perform asynchronous operations and finally submit mutationmethods.

ActionsThe method in has two default parameters

  • context Context (equivalent to this in the arrow function) object
  • payloadMounting parameters
    For example, we execute 2.2.2the editmethod in the section after two seconds

Since it setTimeoutis an asynchronous operation, you need to useactions

actions:{
    
    
    aEdit(context,payload){
    
    
        setTimeout(()=>{
    
    
            context.commit('edit',payload)
        },2000)
    }
}

Call in the component:

this.$store.dispatch('aEdit',{
    
    age:15})

Improve:

Since it is an asynchronous operation, we can encapsulate our asynchronous operation as an Promiseobject

aEdit(context,payload){
    
    
    return new Promise((resolve,reject)=>{
    
    
        setTimeout(()=>{
    
    
            context.commit('edit',payload)
            resolve()
        },2000)
    })
}

2.5 Models

When the project is large and the status is very large, modular management mode can be adopted. Vuex allows us to divide the store into modules. Each module has its own state, , mutation, action, gettermodules and even nested sub - divided from top to bottom the same way.

models:{
    
    
    a:{
    
    
        state:{
    
    },
        getters:{
    
    },
        ....
    }
}

The state of calling module a in the component:

this.$store.state.a

And submit or dispatcha method is the same as before, and the method of the corresponding type in all modules will be automatically executed:

this.$store.commit('editKey')
this.$store.dispatch('aEditKey')

2.5.1 Module details

  • The first parameter accepted by the methods in the module mutationsand gettersin the method is the state inside its own local module
models:{
    
    
    a:{
    
    
        state:{
    
    key:5},
        mutations:{
    
    
            editKey(state){
    
    
                state.key = 9
            }
        },
        ....
    }
}
  • gettersThe third parameter of the method is the state of the root node
models:{
    
    
    a:{
    
    
        state:{
    
    key:5},
        getters:{
    
    
            getKeyCount(state,getter,rootState){
    
    
                return  rootState.key + state.key
            }
        },
        ....
    }
}
  • actionsThe method in the method to obtain the local module state is context.state, and the root node state is context.rootState
models:{
    
    
    a:{
    
    
        state:{
    
    key:5},
        actions:{
    
    
            aEidtKey(context){
    
    
                if(context.state.key === context.rootState.key){
    
    
                    context.commit('editKey')
                }
            }
        },
        ....
    }
}

Three, standardize the directory structure

It is unreasonable to put the whole storein the index.jsmiddle, so it needs to be split. The more suitable directory format is as follows:

store:.
│  actions.js
│  getters.js
│  index.js
│  mutations.js
│  mutations_type.js   ##该项为存放mutaions方法常量的文件,按需要可加入
│
└─modules
        Astore.js

The corresponding content is stored in the corresponding file, as before index.js, stored in and exported store. stateTry to put the data in the index.jsmiddle. And modulesthe Astorelocal modules if the state of many words can also be broken down.

Guess you like

Origin blog.csdn.net/u013034585/article/details/106062696