vue3.0中对mapState,mapGetters封装

看例子,如果没封装,当我们获取state的时候需要这样一个个写

  const sCounter = computed(() => store.state.counter)
  const sName = computed(() => store.state.name)
  const sAge = computed(() => store.state.age)

封装之后这样写

const storeState = useState(["counter", "name", "age"])

开始封装创建一个useMapper.js文件

import { computed } from 'vue'
import { useStore } from 'vuex'

export function useMapper(mapper, mapFn) {
  // 拿到store独享
  const store = useStore()

  // 获取到对应的对象的functions: {name: function, age: function}
  const storeStateFns = mapFn(mapper)

  // 对数据进行转换
  const storeState = {}
  Object.keys(storeStateFns).forEach(fnKey => {
    const fn = storeStateFns[fnKey].bind({$store: store})
    storeState[fnKey] = computed(fn)
  })

  return storeState
}

因为封装mapState和mapGetters逻辑差不多,先看useState.js

import { mapState, createNamespacedHelpers } from 'vuex'
import { useMapper } from './useMapper'

export function useState(moduleName, mapper) {
  let mapperFn = mapState
  if (typeof moduleName === 'string' && moduleName.length > 0) {
    mapperFn = createNamespacedHelpers(moduleName).mapState
  }

  return useMapper(mapper, mapperFn)
}

useGetters.js

import { mapGetters, createNamespacedHelpers } from 'vuex'
import { useMapper } from './useMapper'

export function useGetters(moduleName, mapper) {
  let mapperFn = mapGetters
  if (typeof moduleName === 'string' && moduleName.length > 0) {
    mapperFn = createNamespacedHelpers(moduleName).mapGetters
  }

  return useMapper(mapper, mapperFn)
}

然后使用,当没有用module模块化的时候这样写,直接在页面上{{counter}}.....即可

const storeState = useState(["counter", "name", "age", "height"]);
const storeGetters = useGetters(["nameInfo", "ageInfo", "heightInfo"]);

  return {
     ...storeState,
     ...storeGetters
  }

当用了模块化module之后这样写,假如你的modules有一个home,页面上还是这样用{{homeCounter}}....即可

  const state = useState("home", ["homeCounter"])
  const getters = useGetters("home", ["doubleHomeCounter"])
   return {
    ...state,
    ...getters,
  }
  • 6
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值