Skip to content

Instantly share code, notes, and snippets.

@mikemunsie
Last active July 24, 2023 15:19
Show Gist options
  • Save mikemunsie/3aeaf3602ee1587fa9000c144e440cc7 to your computer and use it in GitHub Desktop.
Save mikemunsie/3aeaf3602ee1587fa9000c144e440cc7 to your computer and use it in GitHub Desktop.
Inject Vue Hook Context into Child Components
import { ref } from "vue";
import useContext from "../utils/useContext";
const useSampleHook = (userDefinedName) => {
const name = ref(userDefinedName);
return {
name,
refreshData,
};
};
export const useSampleHookContext = useContext(useTestHook);
import { provide, inject } from "vue";
let uid = 0;
// Creates a hook that injects the definition into the child components
export default function useContext<T extends any>(definition: T) {
const id = `$_useContext_${++uid}`;
const hook = (...args) => {
const instance = inject(id, null);
if (instance) return instance;
const hook = (definition as any)(...args);
provide(id, hook);
return hook;
};
return hook as T;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment