Skip to content

Instantly share code, notes, and snippets.

@tomscytale
Created February 2, 2023 12:07
Show Gist options
  • Save tomscytale/42cd3fca69ac876a6ab185af49815628 to your computer and use it in GitHub Desktop.
Save tomscytale/42cd3fca69ac876a6ab185af49815628 to your computer and use it in GitHub Desktop.
Shim library allowing namespaced vuex stores to be easily used in Vue3
<script setup lang="ts">
import Loading from '@/components/Loading.vue';
import { computed, onMounted } from 'vue';
import { mapActions, mapState } from '@/store/stateLib';
const { loading, items } = mapState('page');
const { loadItems } = mapActions('page');
const page = computed(() => {
const path = route.path.replace(/^\//, '');
return items.value.find((page: any) => page.url === path);
});
onMounted(async () => {
await loadItems();
});
</script>
import { computed } from 'vue';
import { useStore } from 'vuex';
const mapState = (module: string | undefined) => {
const store = useStore();
return Object.fromEntries(
Object.keys(module !== undefined ? store.state[module] : store.state).map(key =>
module !== undefined
? [key, computed(() => store.state[module][key])]
: [key, computed(() => store.state[key])]
)
);
};
const mapGetters = (module: string | undefined) => {
const store = useStore();
return Object.fromEntries(
Object.keys(store.getters).map(getter =>
module !== undefined && getter.startsWith(module)
? [getter.substring(module.length + 1), computed(() => store.getters[getter])]
: [getter, computed(() => store.getters[getter])]
)
);
};
const mapMutations = (module: string | undefined) => {
const store = useStore();
return Object.fromEntries(
Object.keys(store._mutations[module]).map(mutation =>
module !== undefined && mutation.startsWith(module)
? [mutation.substring(module.length + 1), (value: any) => store.commit(mutation, value)]
: [mutation, (value: any) => store.commit(mutation, value)]
)
);
};
const mapActions = (module: string | undefined) => {
const store = useStore();
return Object.fromEntries(
Object.keys(store._actions).map(action =>
module !== undefined && action.startsWith(module)
? [action.substring(module.length + 1), (value: any) => store.dispatch(action, value)]
: [action, (value: any) => store.dispatch(action, value)]
)
);
};
export { mapState, mapGetters, mapMutations, mapActions };
@Zoybzo
Copy link

Zoybzo commented Mar 23, 2023

Hi, I am using your scripts. I got an error that "storeLib.ts:29 Uncaught (in promise) TypeError: Cannot convert undefined or null to object". After removing '[module]', the problem was solved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment