feat(projects): 添加provide、inject上下文示例

This commit is contained in:
Soybean 2022-07-07 23:21:17 +08:00
parent 1523c7b075
commit a444731e9e
3 changed files with 49 additions and 0 deletions

View File

@ -148,6 +148,11 @@ module.exports = {
group: 'internal',
position: 'before'
},
{
pattern: '@/context',
group: 'internal',
position: 'before'
},
{
pattern: '@/hooks',
group: 'internal',

43
src/context/demo.ts Normal file
View File

@ -0,0 +1,43 @@
import { ref } from 'vue';
import type { Ref } from 'vue';
import { useContext } from '@/hooks';
interface DemoContext {
counts: Ref<number>;
setCounts: (count: number) => void;
}
const { useProvide: useDemoProvider, useInject: useDemoInject } = useContext<DemoContext>();
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();

1
src/context/index.ts Normal file
View File

@ -0,0 +1 @@
export * from './demo';