有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数:
Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
Getter 接受 state 作为其第一个参数:
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
//从数组todos里筛选出done的值为true的
return state.todos.filter(todo => todo.done)
}
}
})
我们组件中只需要通过计算属性computed即可调用。
computed: {
doneTodos {
return this.$store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
}
}
你也可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。
getters: {
// 从数组todos里筛选出id值为你传的参数的
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}