封装hook实现setup中使用mapstate

前言

传统的vue2中我们使用optionsAPI使用mapstate很方便,但是vue3使用setup函数中我们想使用mapstate变得比较繁琐,今天我们来封装一个简单的hook,帮助我们方便的在setup中使用mapstate来进行开发,废话不多说,直接看源码吧。

源码(附解释)

很简单,看看就懂了,大家可以直接拿到项目中使用

//useMapState.js hook

import { useStore, mapState } from "vuex"
import { computed } from "vue"

export function useMapState(mapper) {
    // 拿到store独享
    const store = useStore()
    // 获取到对应的对象的functions: {name: function, age: function}
    const storeStateFns = mapState(mapper)
    const storeState = {}
    // 对数据进行转换
    Object.keys(storeStateFns).forEach(fnKey => {
        //这里绑定this的原因是computed计算属性在进行查找的时候默认会采用this.$store
        //由于setup中没有this绑定(this是undefined),所以我们需要调用bind手动进行绑定
        const fn = storeStateFns[fnKey].bind({ $store: store })
        storeState[fnKey] = computed(fn)
    })
    return storeState
}

使用

<template>
    <div>
        <h2>two组件</h2>
        <h2>使用hook定义的useMapState:{{counter}}--{{age}}--{{name}}--{{height}}</h2>
        <h2>对象写法{{Scounter}}--{{Sname}}</h2>
    </div>
</template>

<script>
import {useMapState} from "../hook/useMapState"
    export default {
        setup(){
            const storeState = useMapState(['counter','name','age','height'])
            const storeState1 = useMapState({
                Scounter:stete => stete.counter,
                Sname:state => state.name
            }) 
            return{
                ...storeState,
                ...storeState1,
            }
        }
    }
</script>

<style scoped>

</style>
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值