学习优先度:★★★★☆
难易度:★★★☆☆
Vuex 获取器用于根据存储状态计算派生状态,类似于 Vue 组件中的计算属性。
下面是一个使用 Vuex 获取器过滤和计算存储数据的示例:
【代码示例】
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
todos: [
{ id: 1, text: 'Learn Vue', done: true },
{ id: 2, text: 'Learn Vuex', done: false },
{ id: 3, text: 'Build something awesome', done: false }
]
},
getters: {
// Get all todos
allTodos: state => state.todos,
text// Get completed todos
completedTodos: state => state.todos.filter(todo => todo.done),
// Get todo count
todoCount: (state, getters) => getters.allTodos.length,
// Get todo by id (curried getter)
getTodoById: state => id => state.todos.find(todo => todo.id === id)
}
})
// In a Vue component
export default {
computed: {
completedTodos() {
return this.$store.getters.completedTodos
},
todoWithId2() {
return this.$store.getters.getTodoById(2)
}
}
}
【执行结果】
When accessed in a component:
console.log(this.completedTodos) // [{ id: 1, text: 'Learn Vue', done: true }]
console.log(this.todoWithId2) // { id: 2, text: 'Learn Vuex', done: false }
Vuex 获取器是 Vuex 状态管理模式的重要组成部分。它们允许你为你的存储定义计算属性,这些属性可以从任何组件访问。这对于在不修改状态的情况下从状态中获取信息特别有用。
关于 Vuex 获取器的要点
获取器定义在 Vuex 商店的获取器对象中。
它们接收状态作为第一个参数,并可选择接收其他获取器作为第二个参数。
获取器可以返回一个接受参数的函数,从而允许动态获取器行为(如 getTodoById 所示)。
在组件中,可以通过 this.$store.getters.getterName 或 mapGetters 辅助程序访问它们。
获取器会根据其依赖关系进行缓存,只有当某些依赖关系发生变化时才会重新评估。
在提供的示例中,我们定义了几个获取器:
allTodos 返回所有待办事项。
completedTodos 会过滤 todos,只返回已完成的 todos。
todoCount 使用另一个获取器来获取待办事项的总数。
getTodoById 则是一个返回函数的卷曲获取器,允许我们通过传递 id 来查找特定的待办事项。
这些获取器可以在组件中轻松使用,为访问和计算状态数据提供了一种简洁高效的方法。
【补充】
Vuex 的获取器类似于 Vue 组件中的计算属性,但针对的是存储状态。
通过缓存结果并仅在必要时重新计算,使用获取器有助于提高性能。
获取器可与组件中的 mapGetters 辅助器结合使用,以简化获取器的使用并提高代码的可读性。
虽然获取器主要用于读取状态,但也可以与操作结合使用,在提交突变之前执行复杂的状态推导。