preface

In traditional VUe2, we use the optionsAPI to use mapState, but in vue3, we use the setup function to use mapState, which is more complicated. Today, we will package a simple hook to help us to use mapState in the setup. Nonsense not to say, look at the source code directly.

Source code (with explanation)

It’s very simple, just look at it, and you can take it and use it in your project

//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
}

Copy the code

use

< template > < div > < h2 > two component < / h2 > < h2 > defined using hook useMapState: {{counter}} - {{age}} - {{name}}, {{height}} < / h2 > {{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>Copy the code