vue3 usa mapState en la configuración

La combinación de mapState y computed se usa en la versión Vue3. Los internautas han escrito mucho. Aquí hay solo una nota de aplicación posterior a la práctica sin entrar en detalles.

crear un gancho

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

usar

<script lang="ts" setup>

import useMapState from "@/hooks/useMapState"

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

Supongo que te gusta

Origin blog.csdn.net/mrhaoxiaojun/article/details/124082989
Recomendado
Clasificación