Files
lingji-work-fe/src/components/xt-chat/xt-bubble/context.ts

81 lines
2.3 KiB
TypeScript
Raw Normal View History

2025-08-21 00:24:36 +08:00
/*
* @Author: RenXiaoDong
* @Date: 2025-08-20 23:17:49
2025-08-21 10:54:18 +08:00
* @Description:
*
2025-08-21 00:24:36 +08:00
*/
import { computed, defineComponent, inject, provide, shallowRef, triggerRef, unref, watch } from "vue";
import type { ComputedRef, InjectionKey } from "vue";
import { objectType } from "@/utils/type";
import type { BubbleContextProps } from "./types";
2025-08-21 10:54:18 +08:00
/**
*
* Vue的依赖注入系统
*/
2025-08-21 00:24:36 +08:00
const BubbleContextKey: InjectionKey<ComputedRef<BubbleContextProps>> =
Symbol('BubbleContext');
2025-08-21 10:54:18 +08:00
/**
* API
* 访
*/
2025-08-21 00:24:36 +08:00
export const globalBubbleContextApi = shallowRef<BubbleContextProps>();
2025-08-21 10:54:18 +08:00
/**
* Hook
* API
*
* @param value -
*/
2025-08-21 00:24:36 +08:00
export const useBubbleContextProvider = (value: ComputedRef<BubbleContextProps>) => {
2025-08-21 10:54:18 +08:00
// 向子组件提供上下文
2025-08-21 00:24:36 +08:00
provide(BubbleContextKey, value);
2025-08-21 10:54:18 +08:00
// 监听上下文变化同步更新全局API
2025-08-21 00:24:36 +08:00
watch(
value,
() => {
globalBubbleContextApi.value = unref(value);
2025-08-21 10:54:18 +08:00
// 触发响应式更新
2025-08-21 00:24:36 +08:00
triggerRef(globalBubbleContextApi);
},
2025-08-21 10:54:18 +08:00
{ immediate: true, deep: true }, // 立即执行,深度监听
2025-08-21 00:24:36 +08:00
);
};
2025-08-21 10:54:18 +08:00
/**
* Hook
* API获取气泡上下文
*
* @returns
*/
2025-08-21 00:24:36 +08:00
export const useBubbleContextInject = () => {
return inject(
BubbleContextKey,
2025-08-21 10:54:18 +08:00
// 如果没有找到注入的上下文使用全局API作为后备
2025-08-21 00:24:36 +08:00
computed(() => globalBubbleContextApi.value || {}),
);
};
2025-08-21 10:54:18 +08:00
/**
*
* 使
*/
2025-08-21 00:24:36 +08:00
export const BubbleContextProvider = defineComponent({
props: {
2025-08-21 10:54:18 +08:00
// 上下文值,支持对象类型验证
2025-08-21 00:24:36 +08:00
value: objectType<BubbleContextProps>(),
},
setup(props, { slots }) {
2025-08-21 10:54:18 +08:00
// 使用计算属性包装props.value确保响应式
2025-08-21 00:24:36 +08:00
useBubbleContextProvider(computed(() => props.value));
2025-08-21 10:54:18 +08:00
// 渲染默认插槽内容
2025-08-21 00:24:36 +08:00
return () => {
return slots.default?.();
};
},
});
export default BubbleContextProvider;