vuex的辅助函数有
- mapState
- mapGetters
- mapMutations
- mapActions
其中mapMutations、mapActions可以在setup中直接展开使用,mapState、mapGetters需要封装一下再使用。
为什么?
因为mapXXX的返回值是函数对象,
mapState、mapGetters无法直接取到变量
封装
import { useStore, mapState, mapGetters } from "vuex";
import { computed } from 'vue';
export function useState(mapArr) {
const store = useStore();
const arrFn = mapState(mapArr);
const storeState = {};
Object.keys(arrFn).forEach(key => {
//组件外部使用$store指向的也是vuex store
const fn = arrFn[key].bind({$store: store});
storeState[key] = computed(fn)
});
return storeState;
}
export function useGetter(mapArr) {
const store = useStore();
const arrFn = mapGetters(mapArr);
const storeGetter = {};
Object.keys(arrFn).forEach(key => {
const fn = arrFn[key].bind({ $store: store });
storeGetter[key] = computed(fn)
})
return storeGetter;
}
组件中使用
<script>
import { computed } from 'vue';
import { useStore, mapMutations,mapActions} from 'vuex';
import { useState, useGetter } from '@/utils/hooks'
export default {
name: 'VuexView',
setup() {
const store = useStore();
return {
/**
* 直接调用
*/
count: computed(() => store.state.count), //state
double_getter: computed(() => store.getters.double), // getters
increment: () => store.commit('increment'), //mutations
async_increment: () => store.dispatch('increment'), //actions
/**
* 使用辅助函数
*/
...useState(["name","age"]), //mapState
...useGetter(["double"]), //mapGetters
...mapMutations(["changeName","changeAge"]), //mapMutations
...mapActions({add: "increment"}) //mapActions
}
}
}
</script>