vuex是什么:
简单来说就是对 应用中组件的状态进行集中式的管理
vuex的核心概念
1. state
vuex管理的状态对象
它应该是唯一的
const state = {
xxx:initValue
}
2. mutations
包含多个state的方法(回调函数)的对象
谁来触发:action中的commit(‘mutation名称’)
注意⚠️:mutations里面只能包含同步的代码,不能写异步代码
const mutation = {
YYY(state,data2){
//更新state的某个属性
}
}
3. actions
包含多个事件回调函数的对象
在内部通过commit() 来触发mutation的调用,间接的更新state
谁来触发:组件中$store.dispatch(‘action名称’,data1) // ‘zzz’
可以包含异步代码,如(定时器、ajax)
const actions = {
zzz({commit,state},data1){
commit('YYY',date2)
}
}
4. getters
包含多个计算属性(get)的对象
谁来读取:组件中:$store.getters.mmm
const getters = {
mmm(state){
return ...
}
}
5. modules
包含多个module
一个module是一个store的配置对象
与一个组件(包含有共享数据)对象
6. 向外暴露store对象
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
7. 组件中
import {mapGetters,mapActions} from 'vuex'
export default(
computed:mapGetters(['mmm']),
methosd:mapActions(['zzz'])
)
8. 映射store
import store from './store'
new Vue({
store
})