Vue3使用Vuex之mapState与mapGetters详解

1.如何使用?

Vue中我们可以通过点语法很容易的获取到Vuexstate的值,但当state数据比较多时,这样很不方便,可以借助mapState映射来简化;由于目前vuex的官网中提供的是Vue2的demo,下面说一下在Vue3中如何使用mapState
假设:在Vuex中的state具有tokenusername属性,现在要通过mapState取得tokenusername

Vue3+JS

<script setup>
import { useStore, mapState } from "vuex";
import { computed } from "vue";
const store = useStore();
const mappers = mapState(["token", "username"]);
const mapData = {}
Object.keys(mappers).forEach((item) => {
 mapData[item] = computed(mappers[item].bind({ $store:store }));
});
console.log(mapData)
// ref类型的mapData对象:{token: ComputedRefImpl, username:ComputedRefImpl}
</script>

Vue3+TS(ps:建议直接使用pinia替代Vuex

<script setup lang="ts">
import { useStore, mapState } from "vuex";
import { computed } from "vue";
import type { Ref } from 'vue'
type mappersType = {
 token:() => any,
 username:() => any,
 [propName:string]:any
}
type mapDataType = {
 token:Ref,
 username:Ref,
 [propName:string]:Ref
}
const store = useStore();
const mappers:mappersType = mapState(["token", "username"]) as mappersType
const mapData:mapDataType = {} as mapDataType;
Object.keys(mappers).forEach((item) => {
 mapData[item] = computed(mappers[item].bind({ $store:store }));
});
console.log(mapData)
// ref类型的mapData对象:{token: ComputedRefImpl, username:ComputedRefImpl}
</script>

2.代码封装

storeMap.js

import { computed } from 'vue';
/**
* 映射store对应的属性(mapState|mapGetters)
* @param $store useStore()
* @param mappers mapState([])|mapGetters([])
* @returns {[propName:string]: ComputedRefImpl,...}
*/
function getStoreMap($store, mappers) {
 const mapData = {}
 Object.keys(mappers).forEach((item) => {
 mapData[item] = computed(mappers[item].bind({ $store })).value;
 });
 return mapData;
}
export { getStoreMap }

使用

<script setup>
import { useStore, mapState, mapGetters } from "vuex";
import { getStoreMap } from './storeMap'
const store = useStore();
const mappers = mapState(["token", "username"]);
// const mappers = mapGetters(["getToken", "getUsername"]); //也可以获取mapGetters
const mapData = getStoreMap(store, mappers)
console.log(mapData) // 包含state或getters属性的ref类型的对象
</script>

3.解题思路

以下是我的一种比较取巧的解题思路,可酌情参考

延用上面的例子
首先,我们先导入mapState,并创建一个空的mapState对象,将鼠标移动至mapState()上查看

可以看到mapState接收的是一个字符串类型的数组,返回的是一个属性为string类型,值为Computed类型的对象,可推导这里mapState接收的应是["token", "username"]
const mappers = mapState(["token", "username"]);

再次将鼠标移动至mappers上,查看mappers类型

可以看到mappers是一个对象;
console.log(mappers.token)查看属性token属性的值是什么

可以看到mappers.token是一个方法;
通过console.log(mappers.token())调用输出这个方法,发现浏览器的控制台报错了

错误提示Cannot read properties of undefined (reading 'state'),点击上图蓝色箭头处查看报错的源代码

可以看出整个截图部分是mapState对象,我们执行mappers.token()是图中标红的区域,再结合报错信息可知报错是因为这里的this对象没有$store属性。
由于this中只有$store被使用,并没有用到this的其他属性,则可以通过bind方式,手动传一个具有store属性的this对象进去,并输出调用


这时我们可以看到token的值已经在浏览器被输出了,然后将bind()后的方法放到computed里执行即可得到Ref类型的token对象。

作者:要吃早餐lhy

%s 个评论

要回复文章请先登录注册