Vue3setup函数中使用Vuex中使用mapState和mapGetters的hooks

Vue3setup函数中使用Vuex中使用mapState和mapGetters的hooks

// useMapper.js 核心
import { computed } from 'vue';
import { useStore } from 'vuex'

// mapper传入的, mapFn是使用的map方法
export function useMapper(mapper, mapFn) {
  // 拿到store对象
  const store = useStore()

  // 获取到对应的对象的function {counter: function, name: function, age: function}
  const storeDataFns = mapFn(mapper)
  // 这些对应的是一个个对象, 函数

  // 对数据进行转换 {counter: ref, name: ref, age: ref}
  const storeData = {}

  // 使用Object.keys获取storeGettersFns的key值
  // 在使用forEach遍历每一个key
  Object.keys(storeDataFns).forEach(fnKey => {
    // 取出storeDataFns中的函数,调用函数的bind绑定一个this,fn就有了this,
    // 这个this必须是个对象,且需要有$store属性,且需要个值
    const fn = storeDataFns[fnKey].bind({$store: store});
    // 取出的函数用computed包裹,根据key重新赋值给storeGetters
    storeData[fnKey] = computed(fn);
  })

  return storeData
}
mapState的使用
// 在setup中使用mapState的hooks
import { mapState, createNamespacedHelpers } from 'vuex'
import { useMapper } from './useMapper'

// 传入一个模块名
export function useState(moduleName, mapper) {
  let mapperFn = mapState
  // 判断传入的模块名是否是String类型,且长度不为0
  if (typeof moduleName === 'string' && moduleName.length > 0) {
    mapperFn = createNamespacedHelpers(moduleName).mapState
  } else {
    mapper = moduleName
  }
  return useMapper(mapper, mapperFn)
}
mapGetters的使用
// 在setup中使用mapGetters的hooks
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
  } else {
    mapper = moduleName
  }
  return useMapper(mapper, mapperFn)
}
应用
<template>
  <div>
    <h2>{{homeCounter}}</h2>
    <h2>{{doubleHomeCounter}}</h2>
    <hr>
    <!-- 没加namespaced: true,的写法 -->
    <!-- <h2>{{$store.getters.doubleHomeCounter}}</h2> -->
    <!-- 加了namespaced: true,后的写法 -->
    <h2>{{$store.getters["home/doubleHomeCounter"]}}</h2>
  </div>
</template>

<script>
  // 写法三
  import { createNamespacedHelpers } from 'vuex'
  const { mapState, mapGetters } = createNamespacedHelpers("home")
  
  import { useState, useGetters } from '../hooks/index'

  export default {

    setup() {
      const state = useState("home", ["homeCounter"])
      const getters = useGetters("home", ["doubleHomeCounter"])

      return {
        ...state,
        ...getters
      }
    }
  }
</script>

<style scoped>

</style>
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值