特性
共享状态解决以下问题:
- 多个组件共享状态state,如兄弟组件之间的状态传递
- 不同组件行为需要更新同一state,但不破坏组件之间的单向数据流
对于简单应用 store模式
- 集中式状态管理
- action统一管理state的更新,更好地记录state的变化和调试
1 | var store = { |
对于大型应用 vuex状态管理
- 全局单例模式管理状态
- 集中式存储管理应用的所有组件的状态
store注入根实例,通过this.$store访问
1 | // 定义单例store |
modules分割模块
1 | // 定义store模块 |
state状态
- 状态存储state是响应式的
- 通过commit提交mutation去改变状态
- 组件可以在计算属性中获取state
1
2// 引用
this.$store.state.module.selectState
getter计算属性
1 | // 定义 |
mutation
- 同步函数
- mutation中变更state
- 通过 this.$store.commit(‘funName’) 提交mutation
1 | // 定义 |
action
- 异步函数
- action中提交mutation变更state
- 通过 this.$store.dispatch() 分发action
1 | // 定义 |