Vuex之理解Getters的用法实例
作者:何凯 时间:2024-05-09 10:42:04
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}`)
// getter的key不允许重复,否则会报错
return
}
store._wrappedGetters[getterKey] = function `wrappedGetter` (store{
// 将每一个getter包装成一个方法,并且添加到store._wrappedGetters对象中,
return rawGetter(
//执行getter的回调函数,传入三个参数,(local state,store getters,rootState)
getNestedState(store.state, modulePath), // local state
//根据path查找state上嵌套的state
store.getters,
// store上所有的getters
store.state
// root state)}})
}
//根据path查找state上嵌套的state
function `getNestedState` (state, path) {
return path.length
? path.reduce((state, key) => state[key], state): state}
来源:https://segmentfault.com/a/1190000009105708
标签:vuex,getters
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Asp WinHttp.WinHttpRequest.5.1 对象使用详解
2012-05-02 10:15:27
Express实现Session身份认证的示例代码
2024-05-08 09:38:21
mysql的in会不会让索引失效?
2024-01-27 11:50:44
OBJECTPROPERTY与sp_rename更改对象名称的介绍
2024-01-19 21:47:46
VS2019 自定义项目模板的实现方法
2022-05-08 21:14:23
![](https://img.aspxhome.com/file/2023/6/112086_0s.png)
网页设计应急小技巧
2011-10-05 18:52:57
Python做屏幕录制工具的实现示例
2021-06-17 09:29:23
导航设计的流行趋势
2007-12-25 12:06:00
![](https://img.aspxhome.com/file/UploadPic/200712/25/2007122512955218s.jpg)
Python的log日志功能及设置方法
2022-03-28 22:13:32
python 中的命名空间,你真的了解吗?
2023-12-23 20:19:58
sql2000数据库清除重复数据的二种方法
2024-01-18 11:08:33
MySql数据库基本命令集会
2011-08-05 18:43:23
Django密码存储策略分析
2022-03-10 04:16:33
Python函数嵌套实例
2022-11-11 06:43:34
python读取和保存视频文件
2023-11-14 06:10:20
python编写softmax函数、交叉熵函数实例
2023-11-24 07:08:11
![](https://img.aspxhome.com/file/2023/6/64606_0s.jpg)
Ubuntu Server 16.04下mysql8.0安装配置图文教程
2024-01-21 21:54:37
![](https://img.aspxhome.com/file/2023/5/95645_0s.png)
永不熄灭的爱心图标——腾讯公益月捐计划 “QQ首席图标”诞生记
2009-09-01 19:43:00
![](https://img.aspxhome.com/file/UploadPic/20099/1/0909_loveplan_banner-44s.jpg)
用ASP在线创建Word与Excel文档
2008-07-20 19:17:00
Python编译为二进制so可执行文件实例
2023-03-05 06:30:36