parent.ts 522 B

12345678910111213141516171819202122
  1. import { getCurrentInstance } from "vue";
  2. /**
  3. * 获取父组件实例
  4. *
  5. * 用于在子组件中获取父组件实例,以便访问父组件的属性和方法
  6. *
  7. * @example
  8. * ```ts
  9. * // 在子组件中使用
  10. * const parent = useParent<ParentType>();
  11. * // 访问父组件属性
  12. * console.log(parent.someProperty);
  13. * ```
  14. *
  15. * @template T 父组件实例的类型
  16. * @returns {T} 返回父组件实例
  17. */
  18. export function useParent<T>(): T {
  19. const { proxy } = getCurrentInstance()!;
  20. return proxy?.$parent as T;
  21. }