【Vue】mapGetters的hooks封装(Vue3)

本文介绍了一种在Vue3中通过自定义Hooks方式来获取Vuex中的多个Getters值的方法。该方法利用了`useStore`和`mapGetters`,并通过`computed`实现状态响应式。此外,还提供了传入数组或对象两种形式的示例。

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

vue2中,可以在计算属性中,直接使用mapGetters从vuex中取出多个状态值,Vue3提供了如何获取多个getters中的值,与取state的值类似,只是调用的方法不同,这里使用的是mapGetters

mapState的使用和封装

mapGetters的hooks封装

封装

目录:src/hooks/useState.js

// useState.js
// useMapper.js
import { useStore, mapGetters } from "vuex";
import { computed } from "vue";

export default function (mapper) {
  // 拿到store

  const store = useStore();

  // 获取相应的对象 : {name:function,gender:function}
  const storeStateFns = mapGetters(mapper);

  // 进行 $store 指向 ,并赋值
  const storeState = {};
  Object.keys(storeStateFns).forEach((Fnkey) => {
    // setup中无this指向
    // 在computed中计算state时需要  $store 指向 ,所以使用bind() 绑定 $store
    const fn = storeStateFns[Fnkey].bind({ $store: store });
    storeState[Fnkey] = computed(fn);
  });

  //返回
  return storeState;
}


使用

传入数组

<script setup>
import useGetters from '@/hooks/useGetters'
//传入数组
const person = useGetters(['getNameInfo', 'getGenderInfo'])
//返回值是对象
console.log(person.name.value);
</script>

传入对象

<script setup>
import useGetters from '@/hooks/useGetters'
//传入数组
const person = useGetters({
			sName:"getNameInfo",
        	sGende:"getGenderInfo"
     	})
//返回值是对象
console.log(person.name.value);
</script>

Vue2的用法

<script>
import { mapGetters } from 'vuex';

export default {
    computed: {
        ...mapGetters([
            'getNameInfo',
            'getGenderInfo'
        ]),
        ...mapGetters([
        //取值使用键名
        	sName:"getNameInfo",
        	sGende:"getGenderInfo"
        ])
    },
};
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值