vuex
State
作用
- Vuex 使用单一状态树——用一个state对象就包含了全部的应用层级状态
访问
- this.$store.state
辅助函数
-
mapState
- 辅助将store中的state映射成组件内部的计算属性
- computed : mapState({count: state => state.count})
- computed : {...mapState(['count'])}
Getter
作用
- store 的计算属性,接受 state 作为其第一个参数,根据state派生出一些状态
访问
- 直接返回getter计算属性:this.store.getters.xxx
- 返回计算属性函数:this.store.getters.xxx()
辅助函数
-
mapGetters
- 将store 中的 getter 映射到组件内的局部计算属性
- computed : mapGetters({count: Count})
- computed : {...mapGetters(['count'])}
Mutation
作用
- 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
使用
- 每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)
- mutations: { increment (state) { // 变更状态 state.count++ } }
- increment是函数的名称,也是 事件类型(type),increment函数本身作为mutation的回调函数
Action
作用
- Action 提交的是 mutation,而不是直接变更状态
- Action 可以包含任意异步操作
分发 Action
- store.dispatch('increment')
- 作用:因为mutation 必须同步执行,因此不采用直接分发 mutation 方式,而使用触发Action。在action中执行异步操作。
组件中分发
- this.$store.dispatch('xxx');// xxx为action name
Module
作用
- Vuex 允许我们将 store 分割成模块(module),避免应用的所有状态会集中到一个比较大的对象而产生的臃肿
命名空间
- 默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 作出响应。
- 添加 namespaced: true 的方式使模块成为带命名空间的模块
模块动态注册
- this.$store.registerModule('name',{state: , getter:,mutation:,action:,module} )
XMind - Trial Version