Vuex之理解Getters的用法实例
2017-04-19 15:15
946 查看
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}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章推荐
- Vuex之理解Mutations的用法实例
- try catch finally 的用法,你知道多少?最详细、最到位的讲解,配合代码实例讲解,让你轻松掌握和理解
- 简单理解vue中实例属性vm.$els
- Vuex之理解mutation的用法
- 理解Vuex的辅助函数mapState, mapActions, mapMutations用法
- vue.js中toast用法及使用toast弹框的实例代码
- 新手对于C#中Dictionary的用法及用途实例理解
- Vue.directive()的用法和实例详解
- vue进行图片的预加载watch用法实例讲解
- Vue.js自定义指令的用法与实例解析
- 深入理解vue $refs的基本用法
- vue.js,基础用法实例
- vue.js计算属性用法(computed)技巧,依赖其他vue实例的数据
- 如何理解Vue的render函数的具体用法
- Vue.js自定义指令的用法与实例
- Vue 中$els 的用法和理解
- vue 组件高级用法实例详解
- vue中$on和$emit用法理解
- Vuex之理解action的用法