-
-
Save michaelegregious/296ec9ebf18482272786140b1dfe0c77 to your computer and use it in GitHub Desktop.
Shim library allowing namespaced vuex stores to be easily used in Vue3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment