vue3.0中对mapState,mapGetters封装
看例子,如果没封装,当我们获取state的时候需要这样一个个写const sCounter = computed(() => store.state.counter)const sName = computed(() => store.state.name)const sAge = computed(() => store.state.age)封装之后这样写const store
·
看例子,如果没封装,当我们获取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,
}
更多推荐
已为社区贡献25条内容
所有评论(0)