在vue3中使用vuex——hooks调用
发表于|更新于
|阅读量:
在 vue3 中的 setup 中使用 vuex,需要使用 computed 进行响应式,如果变量过多,考虑使用 mapState 或者 mapGetters,然而 setup 中没有 this 属性,导致原 vue2 的 computed 扩展写法失效,这里提供一种思路,编写了一个 hooks,使得可以在 setup 中完美使用 vuex。
useMapState
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import { mapState, useStore } from "vuex"; import { computed } from "vue"; export const useMapState = (map) => { const store = useStore();
const storeState = mapState(map);
const states = {}; Object.keys(storeState).forEach((key) => { states[key] = computed(storeState[key].bind({ $store: store })); }); return states; };
|
useMapGetters
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import { mapGetters, useStore } from "vuex"; import { computed } from "vue"; export const useMapGetters = (map) => { const store = useStore();
const storeState = mapGetters(map);
const getters = {}; Object.keys(storeState).forEach((key) => { getters[key] = computed(storeState[key].bind({ $store: store })); }); return getters; };
|
useMapper
我们也可以将上述的函数封装成一个统一的 hook,由用户自行传入 mapper 函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import { useStore } from "vuex"; import { computed } from "vue";
export const useMapper = (mapper, mapperFn) => { const store = useStore();
const storeState = mapperFn(mapper);
const states = {}; Object.keys(storeState).forEach((key) => { states[key] = computed(storeState[key].bind({ $store: store })); }); return states; };
|