feat(projects): 添加provide、inject上下文示例
This commit is contained in:
parent
1523c7b075
commit
a444731e9e
@ -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
43
src/context/demo.ts
Normal 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
1
src/context/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './demo';
|
Loading…
Reference in New Issue
Block a user