vuex 结构图及vuex 核心概念和 API
·
vuex 结构图

vuex 核心概念和 API
1. state
-
- vuex 管理的状态对象
-
- 它应该是唯一的
const state = {
xxx: initValue
}
2. mutations
-
- 包含多个直接更新 state 的方法(回调函数)的对象
-
- 谁来触发: action 中的 commit(‘mutation 名称’)
-
- 只能包含同步的代码, 不能写异步代码
const mutations = {
yyy (state, {data1}) {
// 更新 state 的某个属性
}
}
3. actions
-
- 包含多个事件回调函数的对象
-
- 通过执行: commit()来触发 mutation 的调用, 间接更新 state
-
- 谁来触发: 组件中: $store.dispatch(‘action 名称’, data1) // ‘zzz’
-
- 可以包含异步代码(定时器, ajax)
const actions = {
zzz ({commit, state}, data1) {
commit('yyy', {data1})
}
}
4. getters
-
- 包含多个计算属性(get)的对象
-
- 谁来读取: 组件中: $store.getters.xxx
const getters = {
mmm (state) {
return ...
5. modules
-
- 包含多个 module
-
- 一个 module 是一个 store 的配置对象
-
- 与一个组件(包含有共享数据)对应
6. 向外暴露 store 对象
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
7. 组件中
import {mapState, mapGetters, mapActions} from 'vuex'
export default {
computed: {
...mapState(['xxx']),
...mapGetters(['mmm']),
}
methods: mapActions(['zzz'])
}
{{xxx}} {{mmm}} @click="zzz(data)"
8. 映射 store
import store from './store'
new Vue({
store
})
9. store 对象
-
- 所有用 vuex 管理的组件中都多了一个属性$store, 它就是一个 store 对象
-
- 属性:
state: 注册的 state 对象
getters: 注册的 getters 对象
-
- 方法:
dispatch(actionName, data): 分发调用 action
更多推荐



所有评论(0)