推荐答案
在 Vuex 中,Getter 用于从 store 中派生出一些状态,类似于 Vue 组件中的计算属性。Getter 可以接收 state 作为第一个参数,也可以接收其他 getter 作为第二个参数。Getter 的结果会被缓存,只有当它的依赖值发生改变时才会重新计算。
基本用法
// www.javascriptcn.com code example
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: 'Learn Vue', done: true },
{ id: 2, text: 'Learn Vuex', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done);
},
doneTodosCount: (state, getters) => {
return getters.doneTodos.length;
}
}
});在组件中使用 Getter
// www.javascriptcn.com code example
export default {
computed: {
doneTodos() {
return this.$store.getters.doneTodos;
},
doneTodosCount() {
return this.$store.getters.doneTodosCount;
}
}
};本题详细解读
Getter 的作用
Getter 的主要作用是从 store 中派生出一些状态,这些状态可能是基于 store 中的 state 进行计算的。Getter 类似于 Vue 组件中的计算属性,它们都是基于依赖进行缓存的,只有当依赖发生变化时才会重新计算。
Getter 的参数
- state: Getter 的第一个参数是 state,即 store 中的 state 对象。
- getters: Getter 的第二个参数是 getters,即 store 中的其他 getter。
Getter 的缓存
Getter 的结果会被缓存,只有当它的依赖值发生改变时才会重新计算。这意味着如果多次访问同一个 getter,Vuex 会返回缓存的结果,而不会重复计算。
Getter 的使用场景
- 过滤数据: 例如从 state 中过滤出已完成的任务。
- 计算数据: 例如计算已完成任务的数量。
- 组合数据: 例如将多个 state 或 getter 组合成一个新的状态。
Getter 的高级用法
Getter 还可以返回一个函数,以便在组件中传递参数:
getters: {
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id);
}
}在组件中使用:
// www.javascriptcn.com code example
export default {
computed: {
getTodoById() {
return this.$store.getters.getTodoById;
}
},
methods: {
fetchTodo(id) {
return this.getTodoById(id);
}
}
};通过这种方式,可以在组件中动态地获取 store 中的数据。