Last active
July 24, 2023 15:19
-
-
Save mikemunsie/3aeaf3602ee1587fa9000c144e440cc7 to your computer and use it in GitHub Desktop.
Inject Vue Hook Context into Child Components
This file contains 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 { ref } from "vue"; | |
import useContext from "../utils/useContext"; | |
const useSampleHook = (userDefinedName) => { | |
const name = ref(userDefinedName); | |
return { | |
name, | |
refreshData, | |
}; | |
}; | |
export const useSampleHookContext = useContext(useTestHook); |
This file contains 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 { 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