CNCEC_APP/uni_modules/uview-pro/libs/function/$parent.ts

25 lines
1.0 KiB
TypeScript
Raw Normal View History

2026-03-25 14:54:15 +08:00
// 获取父组件的参数因为支付宝小程序不支持provide/inject的写法
// this.$parent在非H5中可以准确获取到父组件但是在H5中需要多次this.$parent.$parent.xxx
// 这里默认值等于undefined有它的含义因为最顶层元素(组件)的$parent就是undefined意味着不传name
// 值(默认为undefined),就是查找最顶层的$parent
import { type ComponentInternalInstance, getCurrentInstance } from 'vue';
export default function $parent(
componentName?: string,
_instance: ComponentInternalInstance | null | undefined = null
) {
const instance: ComponentInternalInstance | null | undefined = _instance || getCurrentInstance();
let parent = instance && (instance.parent as ComponentInternalInstance | null | undefined);
if (!componentName) return parent;
while (parent) {
const name = (parent.type as any)?.name as string | undefined;
if (name === componentName) {
return parent;
}
parent = parent.parent;
}
return null;
}