本文总结Vuex辅助函数
1 - mapState
返回值是一个对象,对象中包含的是一个个映射函数,所以一般与computed使用。
1.1 - options API 的方式
1.1.1 - 传入数组时
该函数会去Vuex的Store中找到state值进行映射
展示Vuex中的代码
<script>脚本中
这样页面上就可以使用Vuex中的state属性的值,因为一般是通过计算属性来进行缓存,所以用计算属性接收返回内容,然后因为mapState返回的是对象,所以要进行对象的解构。
传入数组会有一个缺陷,就是会出现命名冲突问题。
当组件内定义了重名的data属性,那么组件内的属性优先级大于Vuex属性:
1.1.2 - 传入对象时
为了解决传入数组带来的命名冲突的问题,我们可以选择使用传入对象的方式。
1.2 - composition API 的方式
composition API和options API是有区别的,因为composition API中没有绑定this。所以要进行显示绑定this.$store
1.2.1 - 传入数组/对象
如果我们直接使用mapState返回值的话,得到的是一个个函数。
因为在Options API中,我们就可以知道,mapState返回的是一个对象,对象中是一个个函数,要放在computed中才会触发响应式,并且OptionsAPI中是默认绑定this.$store,所以根据这些特点,我们使用composition API时要改造下代码。
封装成hook
import { computed } from "vue";
import { useStore, mapState } from "vuex";
export default function useState(arg) {
const store = useStore();
const storeState = mapState(arg);
const stateMap = {};
Object.keys(storeState).forEach((key) => {
//绑定$store的值
const effect = storeState[key].bind({ $store: store });
stateMap[key] = computed(effect);
});
return stateMap;
}
2 - mapGetter
vuex代码结构
2.1 - Options API
2.1.1 - 传入数组的方式
那么页面上就可以直接使用getName属性以及getFriend方法
2.1.2 - 传入对象的方式
对象的方式其实就一种方式
2.2 - Composition API
其实与mapState一样,都是会出现的this.$store绑定问题。解决思路也是一样的。因为数组和对象返回的都是映射对象,对象中都是函数,所以参数是数组或者对象没有关系。
封装成hooks
import { useStore, mapGetters } from "vuex";
import { computed } from "vue";
export default function useGetter(arg) {
const store = useStore();
const storeGetter = mapGetters(arg);
const getterMap = {};
Object.keys(storeGetter).forEach((key) => {
const effect = storeGetter[key].bind({ $store: store });
getterMap[key] = computed(effect);
});
return getterMap;
}
3 - mapMutations
vuex代码展示
3.1 - Options API
3.1.1 - 传入数组
3.1.2 - 传入对象
3.2 - Composition API
对于mutations的提交,是不用绑定而外的计算属性的,因为mapMutations返回值就是一个对象,对象中包含着函数,只需要解构对象即可。(传入数组和对象结果一致)
4 - mapActions
这个辅助函数和mapMutations用法一致,区别在于actions本身的特殊性,用于处理异步请求。
5 - createNamespacedHelpers
该函数主要解决问题在使用module中创建的分支时,获取分支的state/getter/mutations/actions问题,起简化操作作用。该函数返回的是一个对象,对象属性包括mapMutations、mapState、mapGetter、mapActions
展示module模块分支:
5.1 - Options API
createNamespacedHelpers传入的参数是模块命名空间的字符串名称。
5.2 - Compositions API
因为上面的已经进行了一层hook封装,只需要修改上面封装的hook就可以了,这样的修改同样包括mapGetter函数。而mapMutations和mapActions正常使用即可。
import { computed } from "vue";
import { useStore, mapState, createNamespacedHelpers } from "vuex";
export default function useState(address, arg) {
const store = useStore();
const stateMap = {};
let storeState = undefined;
if (typeof address === "string" && address.length > 0) {
//这一步判断是否使用命名空间
storeState = createNamespacedHelpers(address).mapState(arg);
} else storeState = mapState(address);
Object.keys(storeState).forEach((key) => {
//绑定$store的值
const effect = storeState[key].bind({ $store: store });
stateMap[key] = computed(effect);
});
return stateMap;
}