2022-07-07 23:21:17 +08:00
|
|
|
|
import { ref } from 'vue';
|
|
|
|
|
import type { Ref } from 'vue';
|
|
|
|
|
import { useContext } from '@/hooks';
|
|
|
|
|
|
|
|
|
|
interface DemoContext {
|
|
|
|
|
counts: Ref<number>;
|
|
|
|
|
setCounts: (count: number) => void;
|
|
|
|
|
}
|
|
|
|
|
|
2022-07-10 00:41:35 +08:00
|
|
|
|
const { useProvide: useDemoProvide, useInject: useDemoInject } = useContext<DemoContext>();
|
2022-07-07 23:21:17 +08:00
|
|
|
|
|
|
|
|
|
export function useDemoContext() {
|
|
|
|
|
const counts = ref(0);
|
|
|
|
|
|
|
|
|
|
function setCounts(count: number) {
|
|
|
|
|
counts.value = count;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const demoContext: DemoContext = {
|
|
|
|
|
counts,
|
|
|
|
|
setCounts
|
|
|
|
|
};
|
|
|
|
|
|
2022-07-10 00:41:35 +08:00
|
|
|
|
function useProvide() {
|
|
|
|
|
useDemoProvide(demoContext);
|
2022-07-07 23:21:17 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
2022-07-10 00:41:35 +08:00
|
|
|
|
useProvide,
|
2022-07-07 23:21:17 +08:00
|
|
|
|
useInject: useDemoInject
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 示例用法: A.vue为父组件, B.vue为子孙组件 C.vue为子孙组件
|
|
|
|
|
// A.vue
|
|
|
|
|
// import { useDemoContext } from '@/context';
|
2022-07-10 00:41:35 +08:00
|
|
|
|
// const { useProvide } = useDemoContext();
|
|
|
|
|
// useProvide();
|
2022-07-07 23:21:17 +08:00
|
|
|
|
|
|
|
|
|
// B.vue 和 C.vue : 共享状态 counts
|
|
|
|
|
// import { useDemoContext } from '@/context';
|
|
|
|
|
// const { useInject } = useDemoContext();
|
|
|
|
|
// const { counts, setCounts } = useInject();
|