源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Vuex之理解Getters的用法实例

  • 时间:2020-03-22 00:42 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Vuex之理解Getters的用法实例
[b]1.什么是getters[/b] 在介绍[url=http://www.1sucai.cn/article/111587.htm]state[/url]中我们了解到,在[code]Store[/code]仓库里,[code]state[/code]就是用来存放数据,若是对数据进行处理输出,比如数据要过滤,一般我们可以写到[code]computed[/code]中。但是如果很多组件都使用这个过滤后的数据,比如饼状图组件和曲线图组件,我们是否可以把这个数据抽提出来共享?这就是[code]getters[/code]存在的意义。我们可以认为,【getters】是store的计算属性。 [b]2.如何使用[/b] 定义:我们可以在[code]store[/code]中定义[code]getters[/code],第一个参数是state
const getters = {style:state => state.style}
传参:定义的[code]Getters[/code]会暴露为[code]store.getters[/code]对象,也可以接受其他的[code]getters[/code]作为第二个参数; 使用:
computed: {
doneTodosCount () {
  return this.$store.getters.doneTodosCount}
[b]3.mapGetters[/b] [code]mapGetters[/code]辅助函数仅仅是将[code]store[/code]中的[code]getters[/code]映射到局部计算属性中,用法和[code]mapState[/code]类似
import { mapGetters } from 'vuex'
computed: {
  // 使用对象展开运算符将 getters 混入 computed 对象中
  ...mapGetters([
  'doneTodosCount',
  'anotherGetter',])}
 //给getter属性换名字
 mapGetters({
 // 映射 this.doneCount 为 store.getters.doneTodosCount
 doneCount: 'doneTodosCount'
})
[b]4.源码分析[/b] [code]wrapGetters[/code]初始化[code]getters[/code],接受3个参数,[code]store[/code]表示当前的[code]Store[/code]实例,[code]moduleGetters[/code]当前模块下所有的[code]getters[/code],[code]modulePath[/code]对应模块的路径
  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}  
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部