vue3 在setup中使用mapState

mapState和computed结合在Vue3版本中使用,广大网友写了很多,这里只做一个实战后的应用笔记,不多赘述

创建一个hook

hooks/useMapState.ts

import {
    
     computed } from "vue"
import {
    
     mapState, useStore } from "vuex"
export default function (state:any) {
    
    
    // 1. 获取实例 $store
    const store = useStore()
    // 2. 遍历状态数据
    const storeStateFns = mapState(state)
    // 3. 存放处理好的数据对象
    const storeState = {
    
    }
    // 4. 对每个函数进行computed
    Object.keys(storeStateFns).forEach(fnKey => {
    
    
        const fn = storeStateFns[fnKey].bind({
    
     $store: store })
        // 遍历生成这种数据结构 => {name: ref(), age: ref()}
        storeState[fnKey] = computed(fn)
    })
    return storeState
}

使用

<script lang="ts" setup>

import useMapState from "@/hooks/useMapState"

const myState:any = useMapState({
    
    
  includeList: (state: any) => state.keepAlive.includeList
})
const {
    
     includeList } = myState
</script>

猜你喜欢

转载自blog.csdn.net/mrhaoxiaojun/article/details/124082989