看例子,如果没封装,当我们获取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,} 热门文章
- 天津宠物领养中心官网招聘 天津宠物领养中心官网招聘信息
- 1月24日19.9M/S|Clash/SSR/V2ray/Shadowrocket免费节点每天更新订阅链接,代理机场推荐
- 3月2日20.1M/S|Clash/V2ray/Shadowrocket/SSR免费节点每天更新订阅链接,代理机场推荐
- 父传子、子传父经典案例—微信小程序自定义标题栏全过程
- 动物疫苗注意事项(动物疫苗使用的注意事项)
- 2月3日21.3M/S|SSR/Clash/V2ray/Shadowrocket免费节点每天更新订阅链接,代理机场推荐
- 3月21日19.1M/S|Clash/SSR/V2ray/Shadowrocket免费节点每天更新订阅链接,代理机场推荐
- 使用maven命令直接打包war项目
- 领养狗狗要求(领养狗的要求)
- 宠物领养市场分析(宠物领养市场分析论文)