Skip to content

refinist/vue-use-forward-ref

Repository files navigation

vue-use-forward-ref

npm Unit Test codecov size

English | 中文

A lightweight Vue 3 composable to forward component ref and merge the child's exposed API onto the parent instance. Parent's ref then exposes both the child's expose() and optional extra fields in one place.

Features

  • Lightweight – Zero dependencies, minimal footprint
  • Type Safe – Full TypeScript support
  • Simple APIuseForwardRef(ext?) returns { forwardRef }, pass it to child's ref
  • Merge with ext – Optionally merge extra fields onto the parent's exposed object

Installation

# npm
npm install vue-use-forward-ref

# yarn
yarn add vue-use-forward-ref

# pnpm
pnpm add vue-use-forward-ref

# bun
bun add vue-use-forward-ref

Basic Usage

Forward child ref to parent

Use forwardRef as the child's ref. The parent's ref (e.g. from a grandparent) will then receive the child's exposed API.

<!-- Wrapper.vue -->
<script setup lang="ts">
import { ref } from 'vue';
import { useForwardRef } from 'vue-use-forward-ref';
import Child from './Child.vue';

const { forwardRef } = useForwardRef();
</script>

<template>
  <Child :ref="forwardRef" />
</template>
<!-- App.vue -->
<script setup lang="ts">
import type Child from './Child.vue';

const wrapperRef = useTemplateRef<InstanceType<typeof Child>>('wrapperRef');
</script>

<template>
  <Wrapper ref="wrapperRef" />
</template>

Merge extra fields

You can merge additional fields onto the exposed object so the parent ref sees both the child's API and your extra data.

// types.ts
import type { Ref } from 'vue';
import type Child from './Child.vue';

export type WrapperExpose = {
  count: Ref<number>;
  reset: () => void;
};
export type WrapperInstance = InstanceType<typeof Child> & WrapperExpose;
<!-- Wrapper.vue -->
<script setup lang="ts">
import { ref } from 'vue';
import { useForwardRef } from 'vue-use-forward-ref';
import Child from './Child.vue';
import type { WrapperExpose } from './types';

const count = ref(0);
const { forwardRef } = useForwardRef<WrapperExpose>({
  count,
  reset: () => {
    count.value = 0;
  }
});
</script>

<template>
  <Child :ref="forwardRef" />
</template>
<!-- App.vue -->
<script setup lang="ts">
import type { WrapperInstance } from './types';
const wrapperRef = useTemplateRef<WrapperInstance>('wrapperRef');
</script>

<template>
  <Wrapper ref="wrapperRef" />
</template>

License

MIT

Copyright (c) 2026-present REFINIST

About

A lightweight Vue 3 composable to forward component ref and merge child exposed API onto parent instance

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors