From a444731e9eef43022930c3550dcfc058e70a2941 Mon Sep 17 00:00:00 2001 From: Soybean Date: Thu, 7 Jul 2022 23:21:17 +0800 Subject: [PATCH] =?UTF-8?q?feat(projects):=20=E6=B7=BB=E5=8A=A0provide?= =?UTF-8?q?=E3=80=81inject=E4=B8=8A=E4=B8=8B=E6=96=87=E7=A4=BA=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .eslintrc.js | 5 +++++ src/context/demo.ts | 43 +++++++++++++++++++++++++++++++++++++++++++ src/context/index.ts | 1 + 3 files changed, 49 insertions(+) create mode 100644 src/context/demo.ts create mode 100644 src/context/index.ts 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';