yanan.wang
Version:
This is a toolset
95 lines (87 loc) • 3.15 kB
JavaScript
import {mapGetters, mapMutations, mapActions, mapState, useStore} from "vuex";
import {computed} from "vue";
/**
*
* @method
* @desc 用于在 setup 语法中代替 mapState
* @param {String} nameSpace (可选)命名空间
* @param {String} arguArr 对应的key列表数组,或者参数列表
* @return 返回值:Object
*/
function mapAuxState (nameSpace, ...arguArr) {
//放在外面的话,会在模块块化预加载词法分析的时候进行调用,但是当时vuex 还没有挂载成功的话会返回undefined,因此需要加入到函数当中
const store = useStore()
validator(nameSpace)
if ( Array.isArray(nameSpace)) arguArr.concat(nameSpace)
const computeState = {}
const states = {...mapState(nameSpace, arguArr.flat())}
Object.keys(states).forEach(key => {
computeState[key.lastIndexOf("/") >= -1 ? key.slice(key.lastIndexOf("/") + 1) : key] = computed(states[key].bind({$store: store}))
})
return computeState
}
/**
*
* @method
* @desc 用于在 setup 语法中代替 mapState
* @param {String} nameSpace (可选)命名空间
* @param {String} arguArr 对应的key列表数组
* @return 返回值:Object
*/
function mapAuxGetters ( nameSpace, ...arguArr) {
const store = useStore()
validator(nameSpace)
if ( Array.isArray(nameSpace)) arguArr.concat(nameSpace)
const computeGetters = {}
const getters = {...mapGetters(nameSpace, arguArr.flat())}
Object.keys(getters).forEach(key => {
computeGetters[key.lastIndexOf("/") >= -1 ? key.slice(key.lastIndexOf("/") + 1) : key] = computed(getters[key].bind({$store: store}))
})
return computeGetters
}
/**
*
* @method
* @desc 用于在 setup 语法中代替 mapMutations
* @param {String} nameSpace (可选)命名空间
* @param {String} arguArr 对应的key列表数组,或者参数列表
* @return 返回值:Array
*/
function mapAuxMutations (nameSpace, ...arguArr) {
const store = useStore()
const methods = []
validator(nameSpace)
if ( Array.isArray(nameSpace)) arguArr.concat(nameSpace)
const mutations = mapMutations(nameSpace, arguArr.flat())
Object.values(mutations).forEach(func => {
methods.push(func.bind({$store: store}))
})
return methods
}
/**
*
* @method
* @desc 用于在 setup 语法中代替 mapActions
* @param {String} nameSpace (可选)命名空间
* @param {String} arguArr 对应的key列表数组,或者参数列表
* @return 返回值:Array
*/
function mapAuxActions (nameSpace, ...arguArr) {
const store = useStore()
const methods = []
validator(nameSpace)
if ( Array.isArray(nameSpace)) arguArr.concat(nameSpace)
const costomActions = mapActions(nameSpace, arguArr.flat())
Object.values(costomActions).forEach(func => {
methods.push(func.bind({$store: store}))
})
return methods
}
function validator(namespace) {
if ( typeof namespace !== "string" && !Array.isArray(namespace)) {
throw new TypeError("the argument Must be a string type or Array")
}
}
export {
mapAuxGetters,mapAuxMutations,mapAuxState,mapAuxActions
}