Files
jindengchen-ai-report/cool-unix/cool/hooks/refs.ts

123 lines
2.7 KiB
TypeScript
Raw Normal View History

2025-11-13 10:36:23 +08:00
import { reactive } from "vue";
import { isNull } from "../utils";
// #ifdef APP
// @ts-ignore
type Instance = ComponentPublicInstance | null;
// #endif
// #ifndef APP
// @ts-ignore
type Instance = any;
// #endif
/**
* Refs 便 API
*/
class Refs {
// 存储所有 ref 的响应式对象key 为 ref 名称value 为组件实例
data = reactive({} as UTSJSONObject);
/**
* ref ref
* @param name ref
* @returns (el: Instance) => void
*/
set(name: string) {
return (el: Instance) => {
this.data[name] = el;
};
}
/**
*
* @param name ref
* @returns null
*/
get(name: string): Instance {
const d = this.data[name] as ComponentPublicInstance;
if (isNull(d)) {
return null;
}
return d;
}
/**
*
* @param name ref
* @param key
* @returns null
*/
getExposed<T>(name: string, key: string): T | null {
// #ifdef APP-ANDROID
const d = this.get(name);
if (isNull(d)) {
return null;
}
// 安卓平台下,$exposed 为 Map<string, any>
const ex = d!.$exposed as Map<string, any>;
if (isNull(ex)) {
return null;
}
return ex[key] as T | null;
// #endif
// #ifndef APP-ANDROID
// 其他平台直接通过属性访问
return this.get(name)?.[key] as T;
// #endif
}
/**
*
* @param name ref
* @param method
* @param data
* @returns
*/
call<T>(name: string, method: string, data: UTSJSONObject | null = null): T {
return this.get(name)!.$callMethod(method, data) as T;
}
/**
*
* @param name ref
* @param method
* @param data
*/
callMethod(name: string, method: string, data: UTSJSONObject | null = null): void {
this.get(name)!.$callMethod(method, data);
}
/**
* open
* @param name ref
* @param data
*/
open(name: string, data: UTSJSONObject | null = null) {
this.callMethod(name, "open", data);
}
/**
* close
* @param name ref
*/
close(name: string) {
return this.callMethod(name, "close");
}
}
/**
* useRefs Refs
* @returns Refs
*/
export function useRefs(): Refs {
return new Refs();
}