mapState和computed结合在Vue3版本中的setup使用

本文介绍了在Vue中如何优化Vuex状态管理,对比了直接使用computed与结合mapState的用法,推荐了一种更高效的方式。通过使用mapState结合computed,可以避免大量重复代码,提高代码可读性和维护性。同时,还提供了一个自定义hook `useMapState`,支持数组和对象两种传参方式,简化了在模板中获取Vuex状态数据的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单的用法: 直接用computed (不推荐)

import {computed} from "vue"
import {mapState, useStore} from "vuex"
export default {
    setup() {
        const store = useStore()
        const counter = computed(() => store.state.counter)
        return {
            counter
        }
    }
}

如果直接用computed的话,后面如果还有很多状态的情况下,你就要写下面这样子的Bad code

const counter = computed(() => store.state.counter)
const name = computed(() => store.state.name)
const age= computed(() => store.state.age)
const counter = computed(() => store.state.counter)
const counter = computed(() => store.state.counter)

神奇的用法: 结合mapState和computed (推荐!拿来吧你!)

import {mapState, useStore} from "vuex"
import {computed} from "vue"
export default {
    setup() {
        const store = useStore()
        const storeStateFns = mapState(['name', 'age', 'gender'])
        /**
         * mapState返回的数据结构:
         * {
         *  name: function(){return 'xxx'},
         *  age: function(){return 'xxx'}
         * }
         */
        const storeState = {}
        Object.keys(storeStateFns).forEach(fnKey => {
            // mapState在解析state的数据时,是需要通过this.$store去解析
            // 在setup里面是没有this的,所以我们给它的函数绑定ctx
            // this => {$store: store}
            const fn = storeStateFns[fnKey].bind({$store: store})
            // 遍历生成这种数据结构 => {name: ref(), age: ref()}
            storeState[fnKey] = computed(fn)
        })

        return {
            ...storeState
        }
    }
}

现在可以在template获取对应的状态数据

<template>
    <h2>setup Name: {{name}}</h2>
	<h2>setup Age: {{age}}</h2>
	<h2>setup Gender: {{gender}}</h2>
</template>

为了方便使用封装为hook

useMapState.js

import { computed } from "vue"
import { mapState, useStore } from "vuex"
export default function (state) {
    // 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
}

使用方式(数组和对象都可食用)

  1. 传入数组形式
import useMapState from "./hooks/useMapState"
export default {
    setup() {
        const state = useMapState(['name', 'age', 'counter'])
        return {
            ...state,
        }
    }
}
  1. 传入对象形式
import useMapState from "./hooks/useMapState"
export default {
    setup() {

        const myState = useMapState({
            myName: state => state.name,
            myAge: state => state.age
        })
        return {
            ...myState
        }
    }
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值