vue3组合式API使用vuex便捷方式

使用state和getter时我们怎么便捷快速的使用

useMapper.js

import { useStore } from 'vuex'
import { computed } from 'vue'
export default function useState(mapper,mapFn){
    const store = useStore()
    const storeStateFns = mapFn(mapper)
    const storeState = {}
    Object.keys(storeStateFns).forEach(fnKey => {
        const fn = storeStateFns[fnKey].bind({$store: store})
        storeState[fnKey] = computed(fn)
    })
    return storeState
}

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
  } else {
    mapper = moduleName
  }

  return useMapper(mapper, mapperFn)
}

useState.js

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

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

  return useMapper(mapper, mapperFn)
}

使用

<template>
    <div>
      {{age}}-----------{{name}} ----------------{{sex}}-----------------{{money}}---{{sumCount}}
    </div>
</template>

<script>
import { useStore } from 'vuex'
import { useGetters } from '../hooks/useGetters'
import  useState  from '../hooks/useState'
export default {
    setup( props , { emit , attrs , slots } ){
        const storeState = useState(["name","age","sex","money"])
        const store = useStore()
        const storeGetters = useGetters(['sumCount'])
        return {
          ...storeState,
          ...storeGetters
        }
    }
}
</script>

<style scoped>

</style>

理解

我们在vue3中一般方式采用const sCounter = computed(() => store.state.counter)进行访问,但是当我们需要访问的元素比较多的时候我们这样写会写成一坨。所以进行封装,那么我们思考一下,我们在computed里写是函数,那么我们也可以使用computed调用函数,在optionsAPI中我们可以写成computed:{...mapState(['counter','name'])},那我们就可以写成:

 const storeState = {}
      Object.keys(storeStateFns).forEach(fnKey => {
        const fn = storeStateFns[fnKey].bind({$store: store})
        storeState[fnKey] = computed(fn)
      })

为啥需要使用bind绑定?
vuex在内部也是通过this.$store.state去拿,那么我们可以通过给函数绑定this达到这个效果。


灵感来自于coderwhy

你可能感兴趣的:(vue.js,前端,javascript)