补充:vuex在vue3中使用mutation/actions/state/getters的几种形式说明*
1.在template直接使用,$store在template中不能识别会飘红但是不影响使用,去掉飘红在d.ts的文件中加上declare const $store:any
2.非辅助函数方式
state 在setup放回的函数中通过key:computed(()=>store.state.值) --->在module中 key:computed(()=>store.state.moduleName[stateName])
getters key:computed(()=>store.getters.值)--->在module中 key:computed(()=>store.getters['moduleName/getterName'])*
mutation key: ()=>{store.commit('mutationMethodName')}--->在module中 key:()=>{store.commit('moduleName/mutationMethodName')}*
actions key: ()=>{store.dispatch('actionMethodName')}--->在module中 key:()=>{store.dispatch('moduleName/actionMethodName')}*
3.辅助函数方式
注意:测试在vue3中mapState跟mapGetters在setup函数返回的对象结构出来的state跟getters是函数,这个函数应该放在computed函数中,其返回值才是我们真正想获取到的响应式的值。特别注意的是这个函数我们在当作参数传递给computed时,我们要显示的为这个函数绑定this为 {$store:store} ;mapMutations跟mapActions在setup直接返回可以在template正常使用*
import {
mapState as mapRootState,
useStore,
mapGetters as mapRootGetters,
createNamespacedHelpers,
} from 'vuex';
import { computed } from 'vue';
export const useState = (*mapper*: string[], *moduleName*?: string) => {
const store = useStore();
let mapFns: Record<string, any>;
const state: Record<string, any> = {};
let mapState;
if (*moduleName*) {
mapState = createNamespacedHelpers(*moduleName*).mapState;
} else {
mapState = mapRootState;
}
mapFns = mapState(*mapper*);
Object.keys(mapFns).forEach(*fnKey* => {
state[*fnKey*] = computed(mapFns[*fnKey*].bind({ $store: store }));
});
return state;
};
export const useGetters = (*mapper*: string[], *moduleName*?: string) => {
const store = useStore();
let mapFn: Record<string, any>;
const getters: Record<string, any> = {};
let mapGetters;
if (*moduleName*) {
mapGetters = createNamespacedHelpers(*moduleName*).mapGetters;
} else {
mapGetters = mapRootGetters;
}
mapFn = mapGetters(mapper);
Object.keys(mapFn).forEach(*key* => {
getters[*key*] = computed(mapFn[*key*].bind({ $store: store }));
});
return getters;
};