ant-design-vue/components/_util/createContext.ts

23 lines
609 B
TypeScript
Raw Normal View History

2022-05-18 14:51:45 +00:00
import { inject, provide, reactive, watchEffect } from 'vue';
2022-05-10 08:18:44 +00:00
2022-05-18 14:51:45 +00:00
function createContext<T extends Record<string, any>>(defaultValue?: T) {
2022-05-10 08:18:44 +00:00
const contextKey = Symbol('contextKey');
2022-05-18 14:51:45 +00:00
const useProvide = (props: T, newProps?: T) => {
const mergedProps = reactive<T>({} as T);
provide(contextKey, mergedProps);
watchEffect(() => {
Object.assign(mergedProps, props, newProps || {});
});
return mergedProps;
2022-05-10 08:18:44 +00:00
};
const useInject = () => {
2022-05-11 13:52:51 +00:00
return inject(contextKey, defaultValue as T) || ({} as T);
2022-05-10 08:18:44 +00:00
};
return {
useProvide,
useInject,
};
}
export default createContext;