const store = new Vuex.Store({
state: {
todos:[
{id:1, text: '...' ,done: true},
{id:2,text:'...',done: false}
] },
getters: {
doneTodos: state => {
return state.todos.filter(todo=> todo.done)
}
}
})Getters 会暴露为store.getters 对象:
store.getters.doneTodos // [{id:1,text: '...',done:true}]Getter 也可以接受其他getters 作为第二个参数:
getters: {
doneTodosCount: (state,getters) => {
return getters.doneTodos.length
}
}
store.getters.doneTodosCount // -> 1
我们可很容易的在任何组件中使用
computed: {
doneTodosCount() {
return this.$store.getters.doneTodosCount
}
}mapGetters 辅助函数
mapGetters 辅助函数仅仅是 store 中的getters 映射到局部计算属性。
import {mapGetter} form 'vuex'
export default {
computed: {
// 使用对象展开运算符将 getters 混入
...mapGetters([
‘doneTodosCount',
'anotherGetter'
])
}
}如果你想讲一个getter 属性另取名字,使用对象性时
mapGetters({
// 映射 this.doneCount 为 store.getters.doneTodosCount
doneCount: 'doneTodosCount'
})Mutations
更改Vuex 的store 中的状态的唯一方式就是提交 mutation Vuex 中的mutation
非常类似于事件,每个 mutation 都有一个字符串的 事件类型 和回调函数。这个回调函数就是我们实际进行状态更改的地方。并且他会接受 state 作为第一个参数。










