单一状态树(用一个对象就包含了所有的应用层级状态),相似于 vue 中的 data
let store = new Vuex.Store({ state: { count: 0 } })
最简单的是在计算属性中返回某个状态,这样每当 store.state 发生变化时,能从新求取计算属性,并触发更新相关联的 DOM。vue
computed: { count () { return this.$store.state.count } }
利用 mapState 辅助函数生成多个计算属性,利用对象展开运算符将 mapState 返回的对象和局部计算属性混合使用。
若同名,能够给 mapState 传一个字符串数组。vuex
import { mapState } from 'vuex' export default { //... computed: { otherComputed () { // 其余局部计算属性 ... }, ...mapState({ countNumber: 'count', // 等于 'countNumber: state => state.count' }) } }
能够从 state 中派生出一些状态,相似于 vue 中的计算属性
接受 state 做为第一个参数,能够接受其余 getter 做为第二个参数,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被从新计算。数组
const store = new Vuex.Store({ state: { todos: [ { id: 1, done: true }, { id: 2, done: false } ] }, getters: { doneTodos: state => { return state.todos.filter(todo => todo.done) }, doneTodosCount: (state, getters) => { return getters.doneTodos.length } } })
// 经过属性访问 this.$store.getters.xxx // 经过方法访问,getter 须要返回一个函数 this.$store.getters.xxx(xx)
import { mapGetters } from 'vuex' export default { computed: { ...mapGetters([ 'doneTodosCount', 'anotherGetter' ]) } }
更改 state 的惟一方式,必须是同步函数
相似 Mutation,但 Action 提交的是 mutation,不能直接改变 state,能够包含异步操做。
Action 函数接受一个 context 对象,该对象与 store 实例具备相同的方法和属性(但不是 store 实例自己),所以能够经过 context.commit 提交一个 mutation,或经过 context.state 和 context.getters 来获取 state 和 getters。
能够经过 ES6 的参数解构来简化代码。缓存
actions: { // context 对象, obj 为载荷(其余参数) action1 (context, obj) { console.log(context) context.commit('xxx') }, // 参数解构 context 对象 action2 ({commit, state, getters}, obj) { console.log(commit, state, getters) } }
// 以载荷形式分发 this.$store.dispatch('updateNumber',{ number: 10 }) // 以对象形式分发 this.$store.dispatch({ type: 'updateNumber', number: 10 })