diff --git a/.eslintrc.js b/.eslintrc.js index 486004ab..1bf14135 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -148,6 +148,11 @@ module.exports = { group: 'internal', position: 'before' }, + { + pattern: '@/context', + group: 'internal', + position: 'before' + }, { pattern: '@/hooks', group: 'internal', diff --git a/src/context/demo.ts b/src/context/demo.ts new file mode 100644 index 00000000..e40d8f6c --- /dev/null +++ b/src/context/demo.ts @@ -0,0 +1,43 @@ +import { ref } from 'vue'; +import type { Ref } from 'vue'; +import { useContext } from '@/hooks'; + +interface DemoContext { + counts: Ref; + setCounts: (count: number) => void; +} + +const { useProvide: useDemoProvider, useInject: useDemoInject } = useContext(); + +export function useDemoContext() { + const counts = ref(0); + + function setCounts(count: number) { + counts.value = count; + } + + const demoContext: DemoContext = { + counts, + setCounts + }; + + function useProvider() { + useDemoProvider(demoContext); + } + + return { + useProvider, + useInject: useDemoInject + }; +} + +// 示例用法: A.vue为父组件, B.vue为子孙组件 C.vue为子孙组件 +// A.vue +// import { useDemoContext } from '@/context'; +// const { useProvider } = useDemoContext(); +// useProvider(); + +// B.vue 和 C.vue : 共享状态 counts +// import { useDemoContext } from '@/context'; +// const { useInject } = useDemoContext(); +// const { counts, setCounts } = useInject(); diff --git a/src/context/index.ts b/src/context/index.ts new file mode 100644 index 00000000..689b5cbc --- /dev/null +++ b/src/context/index.ts @@ -0,0 +1 @@ +export * from './demo';