我认为您想要的是getters。
Vuex允许我们在商店中定义“获取器”。您可以将它们视为商店的计算属性。像计算的属性一样,getter的结果基于其依赖项进行缓存,并且仅在其某些依赖项发生更改时才重新评估。
// store/index.js
export const state = () => ({
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
})
export const getters = {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
mounted() {
// accessing in a component
this.$store.getters.doneTodos
}
查看我链接的文档,其中包含更多示例,包括如何使用基于方法的getter,它们不会缓存结果。
如果您的getter是在模块中定义的,则语法略有不同。您需要执行store.getters['module/doneTodos']
,其中module
是您拥有的存储模块的名称。