在Vue3中,我们常常在Composition Api中使用到vuex的mapState和mapGetters,因为每次获取很麻烦所以就封装了他们,支持模块命名,一键使用,轻松上手

主要实现函数:useMapper.js

import { computed } from "vue"
import { useStore } from "vuex"
// 组合mapState和mapGetters
export default function(data, mapFn) {
    const store = useStore()
    const storeGettersFns = mapFn(data)
    const storeGetters = {}
    Object.keys(storeGettersFns).forEach( fnkey => {
        const fn = storeGettersFns[fnkey].bind({$store: store})
        storeGetters[fnkey] = computed(fn)
    }) 
    return storeGetters
}

两个供调用的函数: useState.js 和 useGetters.js
useGetters.js

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

export default function (name, getters) {
    let mapFn = mapGetters
    if (typeof name === 'string' && name.length > 0) {
        mapFn = createNamespacedHelpers(name).mapGetters
    }
    return useMapper(getters, mapFn)
}

useState.js

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

export default function (name, states) {
    let mapFn = mapState
    if(typeof name === 'string' && name.length > 0 ) {
        mapFn = createNamespacedHelpers(name).mapState
    }
    return useMapper(states, mapFn)
}

使用

写法一:

import useState from "../../hooks/useMapState"
import useGetters from "../../hooks/useGetters"
export default {
    setup(){
    	const mapStoreState = useState(['name', 'age', 'gender'])
        const mapStoreGetters = useGetters(['fullName'])

        return {
            ...mapStoreState,
            ...mapStoreGetters
        }
    },
}

写法二: 如果store使用了模块定义的,用这种写法

import useState from "../../hooks/useMapState"
import useGetters from "../../hooks/useGetters"
export default {
    setup(){
    
        const mapStoreState = useState('user', ['name', 'age', 'gender'])
        const mapStoreGetters = useGetters('user', ['fullName'])

        return {
            ...mapStoreState,
            ...mapStoreGetters
        }
    },
}
Logo

前往低代码交流专区

更多推荐