81 lines
2.3 KiB
TypeScript
81 lines
2.3 KiB
TypeScript
/*
|
||
* @Author: RenXiaoDong
|
||
* @Date: 2025-08-20 23:17:49
|
||
* @Description: 气泡上下文管理
|
||
* 提供气泡组件间的通信机制,支持全局状态管理和组件间数据传递
|
||
*/
|
||
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";
|
||
|
||
/**
|
||
* 气泡上下文注入键
|
||
* 用于Vue的依赖注入系统,确保上下文的唯一性
|
||
*/
|
||
const BubbleContextKey: InjectionKey<ComputedRef<BubbleContextProps>> =
|
||
Symbol('BubbleContext');
|
||
|
||
/**
|
||
* 全局气泡上下文API
|
||
* 提供全局访问气泡上下文的能力,用于跨组件通信
|
||
*/
|
||
export const globalBubbleContextApi = shallowRef<BubbleContextProps>();
|
||
|
||
/**
|
||
* 气泡上下文提供者Hook
|
||
* 向子组件提供气泡上下文,并同步更新全局API
|
||
*
|
||
* @param value - 要提供的上下文值(计算属性)
|
||
*/
|
||
export const useBubbleContextProvider = (value: ComputedRef<BubbleContextProps>) => {
|
||
// 向子组件提供上下文
|
||
provide(BubbleContextKey, value);
|
||
|
||
// 监听上下文变化,同步更新全局API
|
||
watch(
|
||
value,
|
||
() => {
|
||
globalBubbleContextApi.value = unref(value);
|
||
// 触发响应式更新
|
||
triggerRef(globalBubbleContextApi);
|
||
},
|
||
{ immediate: true, deep: true }, // 立即执行,深度监听
|
||
);
|
||
};
|
||
|
||
/**
|
||
* 气泡上下文注入Hook
|
||
* 从父组件或全局API获取气泡上下文
|
||
*
|
||
* @returns 气泡上下文(计算属性)
|
||
*/
|
||
export const useBubbleContextInject = () => {
|
||
return inject(
|
||
BubbleContextKey,
|
||
// 如果没有找到注入的上下文,使用全局API作为后备
|
||
computed(() => globalBubbleContextApi.value || {}),
|
||
);
|
||
};
|
||
|
||
/**
|
||
* 气泡上下文提供者组件
|
||
* 用于在模板中提供气泡上下文,简化使用方式
|
||
*/
|
||
export const BubbleContextProvider = defineComponent({
|
||
props: {
|
||
// 上下文值,支持对象类型验证
|
||
value: objectType<BubbleContextProps>(),
|
||
},
|
||
setup(props, { slots }) {
|
||
// 使用计算属性包装props.value,确保响应式
|
||
useBubbleContextProvider(computed(() => props.value));
|
||
|
||
// 渲染默认插槽内容
|
||
return () => {
|
||
return slots.default?.();
|
||
};
|
||
},
|
||
});
|
||
|
||
export default BubbleContextProvider; |