Vuex之理解Getters的用法实例

2020-06-16 06:16:54易采站长站整理

1.什么是getters

在介绍state中我们了解到,在

Store
仓库里,
state
就是用来存放数据,若是对数据进行处理输出,比如数据要过滤,一般我们可以写到
computed
中。但是如果很多组件都使用这个过滤后的数据,比如饼状图组件和曲线图组件,我们是否可以把这个数据抽提出来共享?这就是
getters
存在的意义。我们可以认为,【getters】是store的计算属性。

2.如何使用

定义:我们可以在

store
中定义
getters
,第一个参数是state


const getters = {style:state => state.style}

传参:定义的

Getters
会暴露为
store.getters
对象,也可以接受其他的
getters
作为第二个参数;

使用:


computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount}

3.mapGetters

mapGetters
辅助函数仅仅是将
store
中的
getters
映射到局部计算属性中,用法和
mapState
类似


import { mapGetters } from 'vuex'
computed: {
// 使用对象展开运算符将 getters 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',])}
//给getter属性换名字
mapGetters({
// 映射 this.doneCount 为 store.getters.doneTodosCount
doneCount: 'doneTodosCount'
})

4.源码分析

wrapGetters
初始化
getters
,接受3个参数,
store
表示当前的
Store
实例,
moduleGetters
当前模块下所有的
getters
modulePath
对应模块的路径


function `wrapGetters` (store, moduleGetters, modulePath) {
Object.keys(moduleGetters).forEach(getterKey => {
// 遍历先所有的getters
const rawGetter = moduleGetters[getterKey] if (store._wrappedGetters[getterKey]) {
console.error(`[vuex] duplicate getter key: ${getterKey}`)