mapState在composition API 中的使用

595 阅读1分钟

在option API 中使用mapState

import { mapState } from 'vuex'

export default {
    computed: {
        ...mapState(['name', 'age', 'height'])
    } 
}

在composition API 中使用mapState

`<template>
    <div>
        <h2>单个获取name: {{sName}}<h2>
        <h2>多个获取name: {{name}}</h2>
    </div>
</template>`

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

exoprt default {
    setup() {
        const store = useStore();
        // 1. 单个获取
        const sName = computed(() => store.state.name)
        const sAge = computed(() => store.state.age)
        const sHeight = computed(() => store.state.height)
        // 如果state中定义的属性较多 使用单个肯定较为麻烦
        
        // 2. 多个获取
        const storeStateFns = mapState(['name', 'age', 'height']) //  {name: fn(), age: fn()}
        // 创建一个存放 ref 的对象
        const storeState = {}
        Object.keys(storeStateFns).forEach(fnKey => {
            // 这里使用bind(),因为computed(fn)内部会执行this.$store.state.xxx,运行时this.$store为空
            // 通过改变每函数的this指向 将hook中获取的store放入,运行时就会从这个对象中获取$store
            const fn = storeStateFns[fnKey].bind({$store: store})
            storeState[fnKey] = computed(fn)
        })
        
        return {
            ...storeState
        }
    }
}