Skip to content

Instantly share code, notes, and snippets.

@hugo-cardoso
Last active November 1, 2022 02:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugo-cardoso/7c8da4f55d521a6288fc7a0f7d2ff06c to your computer and use it in GitHub Desktop.
Save hugo-cardoso/7c8da4f55d521a6288fc7a0f7d2ff06c to your computer and use it in GitHub Desktop.
Vuex hooks from Vue 2.7
<script>
import { defineComponent } from "vue";
import { useVuex } from "./useVuex";
export default defineComponent({
setup() {
const { getState, getAction } = useVuex();
const user = getState("user");
const fetchApiExample = getAction("fetchApiExample", "MyModule");
return {
user,
fetchApiExample
};
}
})
</script>
import { getCurrentInstance, computed } from "vue";
export const useVuex = () => {
const $root = getCurrentInstance().proxy.$root;
const $store = $root.$store;
function getAction(action, namespace) {
return function(...args) {
if (!namespace) {
$store.dispatch(action, ...args);
} else {
$store.dispatch(`${namespace}/${action}`, ...args);
}
};
}
function getState(state, namespace) {
if (!namespace) {
return computed(() => $store.state[state]);
} else {
return computed(() => $store.state[namespace][state]);
}
}
function getGetter(getter, namespace) {
if (!namespace) {
return computed(() => $store.getters[getter]);
} else {
return computed(() => $store.getters[namespace][getter]);
}
}
function registerModule(...args) {
$store.registerModule(...args);
}
function unregisterModule(...args) {
$store.unregisterModule(...args);
}
return {
getAction,
getState,
getGetter,
registerModule,
unregisterModule,
};
}
@humoyun91
Copy link

getCurrentInstance is an internal API and not intended as client usage. There is no guarantee that it will not break in the future. I think Vue core team should provide clear and detailed guide in terms of how to use vuex@4 and vue-router@4 with vue@2.7.x, if composition API is supported in Vue@2.7 then other official packages should support this as well

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