Skip to content

Commit

Permalink
feat(projects): 添加provide、inject上下文示例
Browse files Browse the repository at this point in the history
  • Loading branch information
honghuangdc committed Jul 7, 2022
1 parent 1523c7b commit a444731
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,11 @@ module.exports = {
group: 'internal',
position: 'before'
},
{
pattern: '@/context',
group: 'internal',
position: 'before'
},
{
pattern: '@/hooks',
group: 'internal',
Expand Down
43 changes: 43 additions & 0 deletions src/context/demo.ts
Original file line number Diff line number Diff line change
@@ -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 change: 1 addition & 0 deletions src/context/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './demo';

1 comment on commit a444731

@vercel
Copy link

@vercel vercel bot commented on a444731 Jul 7, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.