vue3.0中对mapState,mapGetters封装

2022年7月3日11:16:41

看例子,如果没封装,当我们获取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'exportfunctionuseMapper(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'exportfunctionuseState(moduleName, mapper){let mapperFn= mapStateif(typeof moduleName==='string'&& moduleName.length>0){
    mapperFn=createNamespacedHelpers(moduleName).mapState}returnuseMapper(mapper, mapperFn)}

useGetters.js

import{ mapGetters, createNamespacedHelpers}from'vuex'import{ useMapper}from'./useMapper'exportfunctionuseGetters(moduleName, mapper){let mapperFn= mapGettersif(typeof moduleName==='string'&& moduleName.length>0){
    mapperFn=createNamespacedHelpers(moduleName).mapGetters}returnuseMapper(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,}
  • 作者:进阶的巨人001
  • 原文链接:https://blog.csdn.net/weixin_45389051/article/details/118639403
    更新时间:2022年7月3日11:16:41 ,共 1644 字。