Vue3中封装setup函数中的mapstate改进封装

由于在vue3 compositionApi中 setup函数无法获取this,在使用vuex的时候获取this.$store.state.xx会比较繁琐,而vuex中的函数mapState返回值为函数类型,无法使用computed直接返回具体的数值(会提示缺失$stote),考虑使用bind函数重新封装mapState返回的函数,通过bind指定一个绑定$store,参数为useStore,从而变成可以被computed调用的函数,返回的直接为ref对象从而在template中直接使用

复制代码
import { computed } from 'vue'
import { mapState, useStore } from 'vuex';
export function useState(arr) {
    const store = useStore()
    const storeStateFns = mapState(arr)
    const storeState = {}
    Object.keys(storeStateFns).forEach(key => {
        const fn = storeStateFns[key].bind("$store", store)
        //执行fn 实质上仍然 执行$store 但无法获取 只能useStore获取-》每个函数绑定this

        storeState[key] = computed(fn)
    })
    return storeState
};
复制代码

 

posted @   Frose  阅读(476)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示