state
const state = {
xxx: initValue
}
mutations
- 包含多个直接更新state的方法(回调函数)的对象
- 由action中的commit('mutation名称')触发
- 只能是同步代码,不可以异步
const mutation = {
xxx(state, { data1 }){
// 更新state的属性
}
}
actions
- 包含多个事件回调函数的对象
- 执行commit()触发mutation调用,间接更新state
- 在组件中用$store.dispatch('action名称', data1)触发
- 可以是异步代码(定时器或者ajax)
const actions = {
xxx({ commit, state }, data) {
commit('yyy', { data1 })
}
}
getters
- 包含多个计算属性(get)的对象
- 由组件中$store.getters.xx读取
const getters = {
xxx(state){
return ...
}
}
modules
- 包含多个module
- 一个module是一个store的配置对象
- 与一个组件(包含有共享数据)对应
- 向外暴露store对象
export default new Vuex.store({
state,
mutations,
actions,
getters
})
组件中简化语法
import { mapState, mapGetters, mapActions } from 'vuex'
export default {
computed: {
...mapState(['xxx']),
...mapGetters(['yyy'])
},
methods: mapActions(['zzz'])
}
// {{ xxx }} {{ yyy }} @click='zzz(data)'
映射store
import store from './store'
new Vue({
store
})
store对象
- 所有用vuex管理的组件中都多了一个属性$store,它是一个store对象
- 属性
- state:注册的state对象
- getters:注册的getters对象
- 方法:dispatch(actionName, data):分发调用action
结构图
![](https://img-blog.csdnimg.cn/20200308185241956.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzE2MDQ5ODc5,size_16,color_FFFFFF,t_70)