First, get to know VueX
1.1 AboutVueX
VueX
It is Vue
a state management tool suitable for use in project development. Imagine that if you frequently use component parameter transfer to synchronize data
values in a project development , once the project becomes very large, managing and maintaining these values will be quite tricky work. To this end, Vue
a unified management tool is provided for these values frequently used by multiple components VueX
. In VueX
existing Vue
projects, we only need to define these values in VueX
, and then they can be used in Vue
the components of the entire project.
1.2 Installation
Since it VueX
is done VueCli
after learning , please refer to the VueCli 2.x
built 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
store
folder under the root directory of the project and create it in the folderindex.js
At this point, the src
folder 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 store
under 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 store
Mount to the Vue
instance 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 state
the 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.
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 state
the method set used to manipulate the data, and the method set that needs to state
be 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
First of all, Vue
if a component VueX
needs to make a request to the backend during the process of calling a certain method, or when an asynchronous operation occurs, the method in dispatch
VueX is required actions
to ensure the synchronization of the data. It can be said that action
the existence is to allow mutations
the 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 state
the operation on the member. Note that 1.3.3
it is mentioned in the section that it is not recommended to directly manipulate state
the members in the component, because the direct modification (for example this.$store.state.name = 'hello'
:) cannot be VueDevtools
monitored.
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
mutations
The methods have default parameters:
([state] [,payload])
state
Is in the currentVueX
objectstate
payload
This 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 mutation
to 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 delete
or xx.xx = xx
form 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
state
The 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 mutation
of 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 mutation
methods.
Actions
The method in has two default parameters
context
Context (equivalent to this in the arrow function) objectpayload
Mounting parameters
For example, we execute2.2.2
theedit
method in the section after two seconds
Since it setTimeout
is 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 Promise
object
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
, getter
modules 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 dispatch
a 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
mutations
andgetters
in the method is the state inside its own local module
models:{
a:{
state:{
key:5},
mutations:{
editKey(state){
state.key = 9
}
},
....
}
}
getters
The 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
}
},
....
}
}
actions
The 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 store
in the index.js
middle, 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
. state
Try to put the data in the index.js
middle. And modules
the Astore
local modules if the state of many words can also be broken down.